我有两个数组
/**
* 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',
........
);
马塞勒斯
It faded on the crowing of the cock.
Some say that ever 'gainst that season comes
Wherein our Saviour's birth is celebrated,
The bird of dawning singeth all night long:
And then, they say, no spirit dares stir abroad;
The nights are wholesome; then no planets strike,
No fairy takes, nor witch hath power to charm,
So hallow'd and so gracious is the time.
霍雷肖
So have I heard and do in part believe it.
But, look, the morn, in russet mantle clad,
Walks o'er the dew of yon high eastward hill:
Break we our watch up; and by my advice,
Let us impart what we have seen to-night
Unto young Hamlet; for, upon my life,
This spirit, dumb to us, will speak to him.
Do you consent we shall acquaint him with it,
As needful in our loves, fitting our duty?
马塞勒斯
Let's do't, I pray; and I this morning know
Where we shall find him most conveniently.
Exeunt
使用
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;
}