如何检查两个数组并搜索匹配的键,并将第一个数组的值与第二个数组的匹配键合并。请帮助我,因为我是新手。
示例:
1st array = {id => 11,name => 'name',age => 18 }
2nd array = {id,name,age,school}
我想通过将匹配值添加到第二个数组
来获得结果2nd array = {id => 11,name => 'name',age => 18,school => }
答案 0 :(得分:1)
试试这个
$a = ['id' => 11,'name' => 'name','age' => 18];
$b = array_flip(['id','name','age','school']);
foreach($b as $key => &$value){
$value = '';
}
$result = array_merge($b, $a);
答案 1 :(得分:0)
一种简单的方法是循环
$first= array('id' => 11,'name' => 'name','age' => 18 );
$second = array('id','name','age','school');
foreach ($second as $value) {
if(isset($first[$value])){
$final[$value] = $first[$value];
}
};
print_r($final);
第二阵列翻转和数组合并
$first = ['id' => 11,'name' => 'name','age' => 18];
$second= array_flip(['id','name','age','school']);
foreach($second as $key => s$value){
$value = '';
}
$result = array_merge($second, $first);
print_r($result);
答案 2 :(得分:0)
使用array_merge
<?php
$array1 = array('id' => '11', 'name' => 'name', 'age' => 18);
$array2 = array('id','name','age','school');
$array3 = array_merge(array_fill_keys($array2, null), $array1);
print_r($array3);
?>