Skip to content
Advertisement

How to map a 2D array to 1D array in PHP

I can’t figure out how to do the following array_map in php. Any help is much appreciated.

Input:

$arrayA = [
    [
        'slug' => 'bob',
        'name' => 'Bob',
        'age' => '10',
    ],
    [
        'slug' => 'alice',
        'name' => 'Alice',
        'age' => '15',
    ],
    [
        'slug' => 'carl',
        'name' => 'Carl',
        'age' => '17',
    ]
]

Desired Output:

$arrayB = [
    'bob' => 'Bob',
    'alice' => 'Alice',
    'carl' => 'Carl'
]

What I have so far:

Here I am mapping to an array and I know it’s not what I want but I can not figure out if there is some syntax for me to return just $x[‘slug’] => $x[‘name’] without the brackets?

$arrayB = array_map(fn($x) => [$x['slug'] => $x['name']], $arrayA);

My current output (not what I want):

$arrayB = [
    [ 'bob' => 'Bob' ],
    [ 'alice' => 'Alice' ],
    [ 'carl' => 'Carl' ]
];

Advertisement

Answer

There is a PHP function that can do exactly what you want: array_column()

$arrayA = [
    [
        'slug' => 'bob',
        'name' => 'Bob',
        'age' => '10',
    ],
    [
        'slug' => 'alice',
        'name' => 'Alice',
        'age' => '15',
    ],
    [
        'slug' => 'carl',
        'name' => 'Carl',
        'age' => '17',
    ]
];

$arrayB = array_column($arrayA, 'name', 'slug');

That will give you:

Array
(
    [bob] => Bob
    [alice] => Alice
    [carl] => Carl
)

Here’s a demo: https://3v4l.org/LGcES

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement