简体   繁体   English

合并两个数组,但不像array_merge

[英]Merge two arrays, but not like array_merge

I have two arrays in php, both have a date value with 7 days. 我在php中有两个数组,都有7天的日期值。 The same in each. 每个都一样。 The rest of the content of the array differs. 数组的其余内容有所不同。 They look a little like this: 他们看起来有点像这样:

Array #1: 数组#1:

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

Array #2: 数组#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: 现在我正在使用这个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! 谢谢!

As mentioned by comments, you can use array_merge() for this. 正如注释所述,您可以使用array_merge() But you will have loop the outer array in order to get it to work, which would be better done with a for loop so you reference both at once: 但是你将循环外部数组以使其工作,这将更好地使用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]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM