在PHP中组合关联数组


<?php
$arrayName1 = array(
'0' => array('name' => 'steve' ,'age' =>51 ) , 
'1' => array('name' => 'john' ,'age' =>48 ) , 
);
$arrayName2 = array(
'0' => array('name' => 'Steve' ,'place' =>'downtown' ), 
'1' => array('name' => 'John' ,'place' =>'New York' ), 
);
$output = array(
'0' => array('name' => 'steve' ,'age' =>51, 'place' =>'downtown'  ), 
'1' => array('name' => 'john' ,'age' =>48 ,'place' =>'New York' ), 
);

期待着组合两个阵列;name";key,并获得样本结果作为$outputarray_merge((未按预期工作。

使用array_replace_recursive

$arrayName1 = array(
'0' => array('name' => 'steve' ,'age' =>51 ) , 
'1' => array('name' => 'john' ,'age' =>48 ) , 
);
$arrayName2 = array(
'0' => array('name' => 'steve' ,'place' =>'downtown' ), 
'1' => array('name' => 'john' ,'place' =>'New York' ), 
);
$out = array_replace_recursive($arrayName1, $arrayName2);
print_r($out);

输出将是

Array (
[0] => Array
(
[name] => steve
[age] => 51
[place] => downtown
)
[1] => Array
(
[name] => john
[age] => 48
[place] => New York
)
)

如果不能保证两个数组中相同的索引会出现相同的名称,则需要在$arrayName2中搜索匹配的name值,然后将该条目中的值合并到$arrayName1:中的值

$names2 = array_map('strtolower', array_column($arrayName2, 'name'));
$output = array();
foreach ($arrayName1 as $array) {
$key = array_search($array['name'], $names2);
if ($key !== false) {
$output[] = $array + $arrayName2[$key];
}
else {
$output[] = $array;
}
}
print_r($output);

输出:

Array
(
[0] => Array
(
[name] => steve
[age] => 51
[place] => downtown
)
[1] => Array
(
[name] => john
[age] => 48
[place] => New York
)
)

3v4l.org 上的演示

试试这个

function combine_array($array1,$array2,$combineProp){
foreach($array1 as $item){
$combinedKey = strtolower($item[$combineProp]);
$combinedArr1[$combinedKey] =  $item;
}
foreach($array2 as $key => $item){
unset($item[$combineProp]);
$combinedKey = strtolower($array2[$key][$combineProp]);
$combinedArr2[$combinedKey] =  $item;
}
foreach($combinedArr1 as $key => $item){
$combinedItem = $item;
if($combinedArr2[$key]){
$combinedItem = array_merge($item,$combinedArr2[$key]);
}
$resultArr[] =  $combinedItem;
}
return $resultArr;
}
$output = combine_array($arrayName1,$arrayName2,'name');

相关内容

  • 没有找到相关文章

最新更新