1

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)
1
  • array_combine() doesn't do what you seem to think it does... simply reading about it in the PHP Docs would have told you this. Commented Nov 18, 2017 at 22:02

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is the most closest answer to the solution I'm looking for, but when I use your code, it only shows 1 user, while there are 2.
@kiarashi as i said in my answer keys for both array should be same you first array has key 0,3 which is why second array is not present in final array or try to reindex keys of your first array before you loop though the data. Like $user_ids = array_values($user_ids);
0

The correct function is array_merge($array1, $array2).

Fore more info read the documentation on array_merge.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.