0

I have two arrays in php, both have a date value with 7 days. The same in each. The rest of the content of the array differs. They look a little like this:

Array #1:

 [0]
    [date] => 2012-05-01
    [value 1] => 3

Array #2:

 [0]
    [date] => 2012-05-01
    [value 2] => 3

I'd like to merge them to get this:

 [0]
    [date] => 2012-05-01
    [value 1] => 3
    [value 2] => 3

Right now I'm using this slop:

$i = 0;
$full_array = array();
foreach ($array_1 as $a) {
    foreach ($array_2 as $b) {
        if ($a['date'] == $b['date']) {
            $full_array[$i] = $a;
            $full_array[$i] += $b;
            $i++;
        }
    }
}

I can turn that guy into a function but before I do I figured I'd check to see if there was a better way. Thanks!

4

1 回答 1

2

正如评论中提到的,您可以使用array_merge()它。但是您将循环外部数组以使其工作,最好使用for循环来完成,因此您可以同时引用两者:

for ($i = 0, $len = count($array_1), $full_array = array(); $i < $len; $i++) {
  $full_array[$i] = array_merge($array_1[$i], $array_2[$i]);
}
于 2012-06-08T22:09:10.790 回答