Search code examples
phparraysmultidimensional-arrayarray-merge

How can I merge one array with values into an array with stdClass objects?


I have two arrays and looking for the way to merge them. Standard array_merge() function don't work.

Do you know any nice solution without foreach iteration?

My first array:

Array
(
    [0] => stdClass Object
        (
            [field_value] => Green
            [count] => 
        )

    [1] => stdClass Object
        (
            [field_value] => Yellow
            [count] => 
        )
)

My second array:

Array
(
    [0] => 2
    [1] => 7
)

And as a result I would like to get:*

Array
(
    [0] => stdClass Object
        (
            [field_value] => Green
            [count] => 2
        )

    [1] => stdClass Object
        (
            [field_value] => Yellow
            [count] => 7
        )
)

Solution

  •  [akshay@localhost tmp]$ cat test.php
     <?php
    
      $first_array = array( 
                (object)array("field_value"=>"green","count"=>null),
                (object)array("field_value"=>"yellow","count"=>null)
                 );
    
      $second_array = array(2,7);
    
    
      function simple_merge($arr1, $arr2)
      {
        return array_map(function($a,$b){ $a->count = $b; return $a; },$arr1,$arr2);
      }
    
      print_r($first_array);
      print_r($second_array);
      print_r(simple_merge($first_array,$second_array));
    
     ?>
    

    Output

     [akshay@localhost tmp]$ php test.php
     Array
     (
         [0] => stdClass Object
             (
                 [field_value] => green
                 [count] => 
             )
    
         [1] => stdClass Object
             (
                 [field_value] => yellow
                 [count] => 
             )
    
     )
     Array
     (
         [0] => 2
         [1] => 7
     )
     Array
     (
         [0] => stdClass Object
             (
                 [field_value] => green
                 [count] => 2
             )
    
         [1] => stdClass Object
             (
                 [field_value] => yellow
                 [count] => 7
             )
    
     )