user1687621
user1687621

Reputation: 433

Merging two flat arrays by shared indexes to create rows in a 2d array

So I have two arrays.

$user_ids = array('123','124','125');
$names = array('john','bob','susie');

Now, all of those arrays are matched up. Meaning that 123 is the user_id for john, 124 is the user_id for Bob, etc. (So both arrays have matching keys)

But I want to end up with a multidimensional array for each user with their user_id and name instead of having them seperate.

[
    ['user_id' => 123, 'name' => 'john'],
    ['user_id' => 124, 'name' => 'bob'],
    ['user_id' => 125, 'name' => 'susie'],
]

Upvotes: 2

Views: 78

Answers (3)

mickmackusa
mickmackusa

Reputation: 47864

Synchronously iterating multiple indexed arrays with the same element count is ideally and concisely performed by array_map().

To elegantly declare the associative keys in each row without repeating yourself (D.R.Y.), declare variables with the desired key name as the text after the $, then call get_defined_vars() in the callback.

Code: (Demo)

$user_ids = ['123', '124', '125'];
$names = ['john', 'bob', 'susie'];

var_export(
    array_map(
        fn($user_id, $name) => get_defined_vars(),
        $user_ids,
        $names
    )
);

Output:

array (
  0 => 
  array (
    'user_id' => '123',
    'name' => 'john',
  ),
  1 => 
  array (
    'user_id' => '124',
    'name' => 'bob',
  ),
  2 => 
  array (
    'user_id' => '125',
    'name' => 'susie',
  ),
)

For anyone seeking a transposed data set as an indexed array of indexed elements, then simply write null as the callback parameter. (Demo)

var_export(
    array_map(null, $user_ids, $names)
);

Output:

array (
  0 => 
  array (
    0 => '123',
    1 => 'john',
  ),
  1 => 
  array (
    0 => '124',
    1 => 'bob',
  ),
  2 => 
  array (
    0 => '125',
    1 => 'susie',
  ),
)

Upvotes: 0

MH2K9
MH2K9

Reputation: 12039

You can try using array_combine() or array_map() according to your demand

$user_ids = array('123','124','125');
$names = array('john','bob','susie');

$new_array = array_combine($user_ids, $names);

or

$new_array = array_map(function($name, $id){
    return array('id'=>$id, 'name'=>$name);}, $names, $user_ids
);

Upvotes: 2

greco.roamin
greco.roamin

Reputation: 807

$multiarr = array("id" => $user_ids, "names" => $names);

Upvotes: -1

Related Questions