[英]How to combine two arrays with same keys?
I have two arrays 我有两个数组
[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")
And I want to combine them in a way that all entries in the 2nd array fetch the value
from the first array, if an entry exists. 我想以一种方式组合它们,以便第二个数组中的所有条目都从第一个数组中获取value
(如果存在)。 So the desired output would be as follows. 因此,所需的输出如下。
[0] => array('date' => "2013-11-26", 'value' => "2")
[1] => array('date' => "2013-11-25", 'value' => "null")
[2] => array('date' => "2013-11-24", 'value' => "6")
I see a way to loop through the second array and then do an innerloop through the first array to check for matching entries: 我看到了一种方法来遍历第二个数组,然后对第一个数组做一个内循环来检查匹配项:
foreach($second as &$s) {
foreach($first as $f) {
if($f['date'] == $s['date']) {
$s['value'] = $f['value'];
}
}
}
But is there no more efficient way to do this, eg a native PHP function that manages an operation like this? 但是,还有没有更有效的方法来执行此操作,例如,管理此类操作的本地PHP函数?
Does array need to be sorted by date? 数组是否需要按日期排序?
Using straightforward foreach https://eval.in/73533 使用简单的foreach https://eval.in/73533
$result = $s = array();
foreach (array_merge($a1, $a2) as $v) {
if (! $s[ $v["date"] ]++) $result[]= $v;
}
or array_filter()
with closure for filtering https://eval.in/73523 , 或带有用于过滤https://eval.in/73523的闭包的array_filter()
,
$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"] ]++;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.