18

我有两个数组

/**
 * Menu Navigation
 * @var array
 */
public $nav_top = array(
    100 => 'Dashboard',
    200 => 'Sell',
    300 => 'Products',
    400 => 'History',
    500 => 'Customers',
    600 => 'Setup'
);

/**
 * Menu Navigation
 * @var array
 */
public $nav_sub = array(
    201 => 'Current Sale',
    202 => 'Retrieve Sale',
    203 => 'Close Register',

    301 => 'Product',
    302 => 'Stock Control',
    303 => 'Price Books',
    304 => 'Types',
    305 => 'Suppliers',
    306 => 'Brands',
    307 => 'Tags',

    501 => 'Customer',
    502 => 'Group'
);

如何组合这两个数组而不丢失它的键索引?

如果我用array_merge()索引做它将从零开始

$nav = array_merge($Class->nav_top, $Class->nav_sub);
var_dump($nav);

# Output:
array(
    0 => 'Current Sale',
    1 => 'Retrieve Sale',
    2 => 'Close Register',
    .......
);

预期结果数组键仍然相同

# Expected Output
array(
    100 => 'Dashboard',
    200 => 'Sell',
    300 => 'Products',
    ........
);
4

2 回答 2

60

我能想到的最简单的:

$combined = $nav_top + $nav_sub;

一个例子

于 2012-04-24T21:02:53.823 回答
1

我的建议

使用jeroen解决方案

艰难的出路

$combined  = merge($nav_top,$nav_sub);

功能

function merge($arr1,$arr2)
{
    if(!is_array($arr1))
        $arr1 = array();
    if(!is_array($arr2))
        $arr2 = array();
    $keys1 = array_keys($arr1);
    $keys2 = array_keys($arr2);
    $keys  = array_merge($keys1,$keys2);
    $vals1 = array_values($arr1);
    $vals2 = array_values($arr2);
    $vals  = array_merge($vals1,$vals2);
    $ret    = array();

    foreach($keys as $key)
    {
        list($unused,$val) = each($vals);
        $ret[$key] = $val;
    }

    return $ret;
}

或者

function merge($a1, $a2) {

    $aRes = $a1;
    foreach ( array_slice ( func_get_args (), 1 ) as $aRay ) {
        foreach ( array_intersect_key ( $aRay, $aRes ) as $key => $val )
            $aRes [$key] += $val;
        $aRes += $aRay;
    }
    return $aRes;
}

演示:http ://codepad.org/9B8V96Gf

于 2012-04-24T21:11:47.590 回答