phparrayssliceunsetsub-array

Remove unwanted elements from subarrays in multidimensional array


I have a multidimensional array like this:

[
    [
        'id' => 1,
        'name' => 'John',
        'address' => 'Some address 1'
        'city' => 'NY'
    ],
    [
        'id' => 2,
        'name' => 'Jack',
        'address' => 'Some address 2'
        'city' => 'NY'
    ]
    ...
  
    [ ... ]
]

How can I remove elements in all subarrays and only retain the id and name keys with their values?


Solution

  • Would this work?

    $result = array_map(function($arr) {
        return [
            'id' => $arr['id'],
            'name' => $arr['name']
        ];
    }, $orig_array);