0

I'm trying to use an array function (I thought about array_map() or array_walk(), but couldn't get it to do what I want) in order to create an array using a multidimensional array (Like a MySQL result) turning a field from the array into the key of the new one.

Say I have an array like this one:

$a = array(
    0 => array( 'id' => 1, 'name' => 'john' ), 
    1 => array( 'id' => 28, 'name' => 'peter' )
);

And I'd like to get another array like this:

$b = array(
    1 => array( 'name' => 'john' ), 
    28 => array( 'name' => 'peter' )
);

I can solve it with a simple foreach loop, but I wonder whether there's a more efficient way, using a built-in function.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Muc
  • 1,464
  • 2
  • 13
  • 31

3 Answers3

1

array_map and array_walk don't allow you to change keys. A foreach loop is definitely the way to go. Foreach can even be more efficient than array_walk/array_map a lot of the time.

mfonda
  • 7,873
  • 1
  • 26
  • 30
0

You Can use array_column function The Output its close to what you want

array_column($a, null, 'id')
Barkati.med
  • 620
  • 5
  • 11
  • To clarify for researchers, this answer will apply `id ` values as first level keys without changing the associative data within each row. (It does not provide the desired result in the asked question.) – mickmackusa Dec 15 '22 at 21:13
0

This task can actually be done with a "body-less" foreach() loop.

Using "array destructuing" to define variables and square-brace pushing syntax, the entire operation can be written in the foreach() signature.

Code: (Demo)

$result = [];
foreach ($a as ['id' => $id, 'name' => $result[$id]['name']]);

var_export($result);

If a functional approach is preferred, then array_reduce() is capable of writing first level keys to the output array.

Code: (Demo)

var_export(
    array_reduce(
        $a,
        fn($result, $row) => array_replace($result, [$row['id'] => ['name' => $row['name']]]), 
        []
    )
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136