Combine two different dimensional arrays PHP

后端 未结 4 1799
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 05:18

I have two different dimensional arrays.

Array 1:

Array1 
(
[0] => Array
    (
        [id] => 123 
        [price] => 5
        [purchase_         


        
相关标签:
4条回答
  • 2021-01-20 05:36

    If the $array1 and $array2 are mapped by the same indexes, so they have same length, you can try:

    foreach($array2 as $index=>$quantity){
      $array1[$index]['Qty'] = $quantity;
    }
    

    And it´s done! If you want to keep the original $array1 untouched, you can make a copy before the foreach.

    0 讨论(0)
  • 2021-01-20 05:41

    Create new array and store it there. You can access the value of $array2 because they have the same index of $array1 so you can use the $key of these two arrays.

       $array3 = [];
       foreach($array1 as $key => $val) {
         $array3[] = [
           'id' => $val['id'],
           'price' => $val['price'],
           'purchase_time' => $val['purchase_time'],
           'Qty' => $array2[$key]
         ];
       }
    
      print_r($array3);
    
    0 讨论(0)
  • 2021-01-20 05:52

    Might be a simpler way, but for fun without foreach:

    array_walk($array1, function(&$v, $k, $a){ $v['Qty'] = $a[$k]; }, $array2);
    
    0 讨论(0)
  • 2021-01-20 05:54

    The simplest way is:

    $i = 0;
    foreach($array1 as &$row) {
        $row['Qty'] = $array2[$i++];
    }
    

    Or if keys of both arrays are the same (0,1,2...) and array have the same length:

    foreach($array1 as $k => &$row) {
        $row['Qty'] = $array2[$k];
    }
    
    0 讨论(0)
提交回复
热议问题