我试图想出一种方法,将具有不同键名的两个数组组合在一起,使用相同的值?匹配值的顺序可能不同,因此需要检查它是否匹配,然后合并,如果是。有一个简单的方法来完成吗?任何帮助或指导表示赞赏。
阵列1
Array
(
[0] => Array
(
[location_id] => 1
[location_title] => Centralia
[location_slug] => Centralia
[state_name] => Illinois
)
[1] => Array
(
[location_id] => 3
[location_title] => Columbia
[location_slug] => columbia
[state_name] => Illinois
)
[2] => Array
(
[location_id] => 15
[location_title] => Dixon Hennepin
[location_slug] => dixon-hennepin
[state_name] => Illinois
)
)
数组2
Array
(
[0] => Array
(
[hours_locationid] => 3
)
[1] => Array
(
[hours_locationid] => 1
)
[2] => Array
(
[hours_locationid] => 15
)
)
结果
Array
(
[0] => Array
(
[location_id] => 1
[location_title] => Centralia
[location_slug] => Centralia
[state_name] => Illinois
[hours_locationid] => 1
)
[1] => Array
(
[location_id] => 3
[location_title] => Columbia
[location_slug] => columbia
[state_name] => Illinois
[hours_locationid] => 3
)
[2] => Array
(
[location_id] => 15
[location_title] => Dixon Hennepin
[location_slug] => dixon-hennepin
[state_name] => Illinois
[hours_locationid] => 15
)
)
答案 0 :(得分:0)
foreach($array1 as $i => $data) {
if(array_search(array('hours_locationid'=>$data['location_id']), $array2) !=== false)
$array1[$i]['hours_locationid'] = $data['location_id'];
}
答案 1 :(得分:0)
foreach ($array1 as $val1) {
foreach ($array2 as $key => $val2) {
if ($val1['location_id'] == $val2['hours_locationid']) {
$val1['hours_locationid'] = $val2['hours_locationid'];
$results[] = $val1;
unset($array2[$key]);
}
}
}
var_dump($results);
应该有效,尽管在评论中提到这是非常简单的
答案 2 :(得分:0)
请尝试以下操作,
替换$ array1和$ array2 - >演示:http://codepad.org/1inDuoVe
<?php
$array1 = array(array("a"=>"aaa","b"=>"bbb"),array("x"=>"xxx","y"=>"yyy"));
$array2= array(array("c"=>"ccc"),array("z"=>"zzz"));
$i=0;
$j=0;
foreach($array2 as $single){
foreach($array1 as $multiple){
if($i == $j){
$keys = array_keys($single);
print $key = $keys[0];
$multiple = array_push_assoc($multiple,$key,$single[$key]);
$array1[$j] = $multiple;
}
++$j;
}
++$i;
}
var_dump($array1);
function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
?>