我有2个数组。我想合并它们。
数组1:
Array
(
[100] =>
[50] =>
[CREDIT] => 14.31
[CHEQUE] =>
)
数组2:
Array
(
[0] => Array
(
[id] => 501
)
[1] => Array
(
[id] => 502
)
[2] => Array
(
[id] => 503
)
我将这些结果与$array1+$array2
合并后得到此结果:
Array
(
[100] =>
[50] =>
[CREDIT] => 14.31
[CHEQUE] =>
[0] => Array
(
[id] => 501
)
)
我的预期结果是:
Array
(
[100] =>
[50] =>
[CREDIT] => 14.31
[CHEQUE] =>
[0] => Array
(
[0] => Array
(
[id] => 501
)
[1] => Array
(
[id] => 502
)
[2] => Array
(
[id] => 503
)
)
)
可能是什么原因?感谢。
答案 0 :(得分:0)
在您的具体案例中,正如$ Sadiq所提到的,我只会做$array1[0] = $array2
。
$arr1 = [
'100' => '',
'50' => '',
'CREDIT' => 14.31,
'CHEQUE' => ''
];
$arr2 = [
'0' => [
'id' => 501
],
'1' => [
'id' => 502
],
'2' => [
'id' => 503
],
];
$arr1[0] = $arr2;
print_r($arr1);
<强>输出强>
Array
(
[100] =>
[50] =>
[CREDIT] => 14.31
[CHEQUE] =>
[0] => Array
(
[0] => Array
(
[id] => 501
)
[1] => Array
(
[id] => 502
)
[2] => Array
(
[id] => 503
)
)
)
答案 1 :(得分:0)
$arr1= array(100=>'',50=>'','CREDIT'=>14.31,'CHEQUE'=>'');
print_r($arr1);
$arr2 = array(0 => array('id' => 501),1 => array ( 'id' => 502),2 => array('id'=> 503));
print_r($arr2);
$result = $arr1 + array($arr2);
print_r($result);
结果:
Array
(
[100] =>
[50] =>
[CREDIT] => 14.31
[CHEQUE] =>
)
Array
(
[0] => Array
(
[id] => 501
)
[1] => Array
(
[id] => 502
)
[2] => Array
(
[id] => 503
)
)
Array
(
[100] =>
[50] =>
[CREDIT] => 14.31
[CHEQUE] =>
[0] => Array
(
[0] => Array
(
[id] => 501
)
[1] => Array
(
[id] => 502
)
[2] => Array
(
[id] => 503
)
)
)
答案 2 :(得分:0)
这些将适用于您需要的任意数量的阵列以及所需的维数。
对于这些函数,将最高优先级数组设置为最低索引:
function overlapArrays($array) {
if(count($array) > 1) {
for($i = (count($array) - 1);$i >= 0;$i--) {
if(($i - 1) >= 0) {
prioritize($array[$i], $array[$i - 1]);
}
else {
break;
}
}
return $array[0];
}
else {
return $array;
}
}
function prioritize($arr1, &$arr2) {
foreach($arr1 as $key => $value) {
if(!array_key_exists($key, $arr2)) {
$arr2[$key] = $value;
}
elseif(is_array($value) && is_array($arr2[$key])) {
prioritize($value, $arr2[$key]);
}
}
}
$array1 = [
100 => '',
50 => '',
'CREDIT' => 14.31,
'CHEQUE' => ''
];
$array2 = [
0 => [
'id' => 501
],
1 => [
'id' => 502
],
2 => [
'id' => 503
]
];
$merger = Array($array1, $array2);
$results = overlapArrays($merger);
例如,如果要将第一个数组和第二个数组中存在的键保留在第一个数组中,则将第一个数组分配给合并数组中的0索引。如果希望array2在匹配时保留值,则将array2分配给0索引。
$array1 = Array(
'one' => Array(
'two' => 2,
'three' => 3
)
);
$array2 = Array(
'one' => Array(
'two' => 3,
)
);
$merger = Array($array2, $array1);
$results = overlapArrays($merger);
results =
Array(
'one' => Array(
'two' => 3,
'three' => 3
)
);
合并数组中索引最高的数组具有最低优先级。合并数组中索引最低的数组具有最高优先级。如果您有足够的问题,请告诉我。我正在努力确保我解释得很好。