所以我有两个数组。一个新旧的。我想用旧数组中的变量更新新数组,但我不想添加新数组中新数组中没有的新索引。
$old_array = array("1" => "one", "2" => "two", "3" => "three", "4" => "four");
$new_array = array("1" => "1", "2" => "2", "3" => "3");
所以我希望新数组为:
$updated_array = array("1" => "one", "2" => "two", "3" => "three");
有没有人可以帮我找到最有效的方法呢?
答案 0 :(得分:2)
可以尝试使用foreach()
。例如:
$old_array = array("1" => "one", "2" => "two", "3" => "three", "4" => "four");
$new_array = array("1" => "1", "2" => "2", "3" => "3");
$updated_array = array();
foreach($new_array as $key=>$val){
if(isset($old_array[$key])){
$updated_array[$key] = $old_array[$key];
}
}
print '<pre>';
print_r($updated_array);
print '</pre>';
答案 1 :(得分:0)
您可以使用foreach
方法(提供键值文档):
以下是PHP文档(http://php.net/manual/en/control-structures.foreach.php)
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
答案 2 :(得分:0)
您可以尝试
$result = array_intersect_key($old_array, $new_array);
答案 3 :(得分:0)
我真的想给@void-main正确答案,但他犯了一些我必须解决的轻微错误,他并没有最终更新它。谢谢你,帮助我开始吧!
$old_array = array("1" => "one", "2" => "two", "3" => "three", "4" => "four");
$new_array = array("1" => "1", "2" => "2", "3" => "3");
foreach($new_array as $key=>$val){
if(isset($old_array[$key]))
$new_array[$key] = $old_array[$key];
}
//new_array is now the updated array.
这样,即使在old_array中不明显,新数组仍将保留所有值