我有两个数组
[0] => array('date' => "2013-11-26", 'value' => "2")
[1] => array('date' => "2013-11-24", 'value' => "6")
# Note there is no entry for "2013-11-25"
[0] => array('date' => "2013-11-26", 'value' => "null")
[1] => array('date' => "2013-11-25", 'value' => "null")
[2] => array('date' => "2013-11-24", 'value' => "null")
我想以一种方式组合它们,以使第二个数组中的所有条目都从第一个数组中获取value
(如果存在)。因此,所需的输出如下。
[0] => array('date' => "2013-11-26", 'value' => "2")
[1] => array('date' => "2013-11-25", 'value' => "null")
[2] => array('date' => "2013-11-24", 'value' => "6")
我看到了一种循环遍历第二个数组,然后对第一个数组做一个内循环以检查匹配项的方法:
foreach($second as &$s) {
foreach($first as $f) {
if($f['date'] == $s['date']) {
$s['value'] = $f['value'];
}
}
}
但是,还有没有更有效的方法来执行此操作,例如,管理此类操作的本机PHP函数?
数组是否需要按日期排序?
使用简单的foreach https://eval.in/73533
$result = $s = array();
foreach (array_merge($a1, $a2) as $v) {
if (! $s[ $v["date"] ]++) $result[]= $v;
}
或array_filter()
关闭过滤https://eval.in/73523,
$a1 = array(
0 => array('date' => "2013-11-26", 'value' => "2"),
1 => array('date' => "2013-11-24", 'value' => "6"),
);
$a2 = array(
0 => array('date' => "2013-11-26", 'value' => "null"),
1 => array('date' => "2013-11-25", 'value' => "null"),
2 => array('date' => "2013-11-24", 'value' => "null"),
);
$s = array();
$result = array_filter(array_merge($a1, $a2), function($v) use (&$s) {
return !$s[ $v["date"] ]++;
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句