简体   繁体   中英

How to map a 2D array to 1D array

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' ]
];

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

With array_map you cant generate a array with the schema what you want. Use instead array_map foreach. like that:

<?php

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

$arrayB = [];
foreach($arrayA as $i) {
  $arrayB[$i['slug']] = $i['name'];
}

print_r($arrayB);

// output: 
/* Array ( 
  [bob] => Bob 
  [alice] => Alice 
  [carl] => Carl 
) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM