Search code examples
phparraysmultidimensional-arraytransposemerging-data

Merge two flat arrays with the same count to form an array of associative arrays


I'm trying to create a list of users with the most sales and I'd like to find a way to combine two arrays.

$user_ids = sample_one();
$user_sales = sample_two();

var_dump on both sample functions:

array(2) { 
    [0]=> string(1) "1" // user ID
    [3]=> string(1) "3" 
} 

array(2) { 
    [0]=> int(5) // User sales
    [1]=> int(20) 
}

In the end I'd like to combine these two arrays. Something like this:

 $users =  array (
      array (
        'id' => '1',
        'sale' => '5'
      )
      array (
        'id' => '3',
        'sale' => '20'
      ),
    )

I tried using array_combine( $user_ids, $user_sales ); but that didn't work. Any alternatives? Eventually I'll end up using it as

array_sort($users, 'sale', SORT_DESC)

Solution

  • I guess there is no such builtin method available you need to loop through your data and create your array

    $data= array();
    
    foreach($user_ids as $key=> $val){
    
        if(isset($user_sales[$key])){
            $data[] = array (
                'id' => $val,
                'sale' => $user_sales[$key]
              );
        }
    
    }
    

    Also make sure keys for both array should be same to map correct data for each user id