dialogik
dialogik

Reputation: 9552

How to combine two arrays with same keys?

I have two arrays

First array

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

Second 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")

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. So the desired output would be as follows.

Desired output

[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, e.g. a native PHP function that manages an operation like this?

Upvotes: 0

Views: 95

Answers (1)

mpapec
mpapec

Reputation: 50647

Does array need to be sorted by date?

Using straightforward 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,

$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"] ]++;
});

Upvotes: 1

Related Questions