Search code examples
phparrayscodeigniter

combine associative arrays in PHP


<?php
$arrayName1 = array(
    '0' => array('name' => 'steve' ,'age' =>51 ) , 
    '1' => array('name' => 'john' ,'age' =>48 ) , 
);

$arrayName2 = array(
    '0' => array('name' => 'Steve' ,'place' =>'downtown' ), 
    '1' => array('name' => 'John' ,'place' =>'New York' ), 
);

$output = array(
    '0' => array('name' => 'steve' ,'age' =>51, 'place' =>'downtown'  ), 
    '1' => array('name' => 'john' ,'age' =>48 ,'place' =>'New York' ), 
);

Looking forward to combine two arrays wrt the "name" key, and obtain the sample result as $output. array_merge() isn't working as expected.


Solution

  • If there is no guarantee that the same names will occur at the same indexes in the two arrays, you need to search for the matching name value in $arrayName2 and then merge the values from that entry into the value from $arrayName1:

    $names2 = array_map('strtolower', array_column($arrayName2, 'name'));
    $output = array();
    foreach ($arrayName1 as $array) {
        $key = array_search($array['name'], $names2);
        if ($key !== false) {
            $output[] = $array + $arrayName2[$key];
        }
        else {
            $output[] = $array;
        }
    }
    print_r($output);
    

    Output:

    Array
    (
        [0] => Array
            (
                [name] => steve
                [age] => 51
                [place] => downtown
            )
        [1] => Array
            (
                [name] => john
                [age] => 48
                [place] => New York
            )
    )
    

    Demo on 3v4l.org