簡體   English   中英

如何將兩個數組與相同的鍵組合?

[英]How to combine two arrays with same keys?

我有兩個數組

第一個數組

[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;

}

或帶有用於過濾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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM