add two arrays together, maintain indexes

自作多情 提交于 2019-12-24 20:15:23

问题


I have two arrays which I want to join together.

I want to preserve the indexes.

First Array (start times)

    array(2) {
      [0]=>
      array(2) {
        ["ID"]=>
        string(2) "15"
        ["start_time"]=>
        string(19) "2012-06-24 08:00:00"
      }
      [1]=>
      array(2) {
        ["ID"]=>
        string(2) "28"
        ["start_time"]=>
        string(19) "2012-07-26 18:00:00"
      }
    }

Second Array (end times)

    array(2) {
      [0]=>
      array(2) {
        ["ID"]=>
        string(2) "15"
        ["end_time"]=>
        string(19) "2012-06-24 17:00:59"
      }
      [1]=>
      array(2) {
        ["ID"]=>
        string(2) "28"
        ["end_time"]=>
        string(19) "2012-07-26 22:00:59"
      }
    }

If I run;

    $merge[0] = $a[0] + $b[0];

    echo '<pre>';
    var_dump($merge);
    echo '</pre>';

I get;

   array(1) {
     [0]=>
     array(3) {
       ["ID"]=>
       string(2) "15"
       ["start_time"]=>
       string(19) "2012-06-24 08:00:00"
       ["end_time"]=>
       string(19) "2012-06-24 17:00:59"
     }
   }

How do I continue this trend? I can only figure out how to target one index ( [0] ) at a time, I know a foreach loop is required to finish it off but unsure how to write it.

Regards


回答1:


Try this:

for ($i=0; $i<count($a); $i++)
{
  $merge[$i] = $a[$i] + $b[$i];
}



回答2:


You will need to use array_merge().

http://php.net/manual/en/function.array-merge.php

Hope it helps.




回答3:


Foreach loop will look like this.

$merge = array();
for($i =0; $i<count($a); $i++)
   $merge[$i] = $a[$i] + $b[$i];



回答4:


$array1, $array2, $result = array();
foreach($array1 as $ind => $item)
    $result[$ind] = array( 
        'ID' => $item['ID'], 
        'start_time' => $item['start_time'], 
        'end_time' => $array2[$ind]['end_time']
    );


来源:https://stackoverflow.com/questions/11665355/add-two-arrays-together-maintain-indexes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!