2

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Johan
  • 23
  • 2

3 Answers3

4

Would this work?

$result = array_map(function($arr) {
    return [
        'id' => $arr['id'],
        'name' => $arr['name']
    ];
}, $orig_array);
nkkollaw
  • 1,947
  • 1
  • 19
  • 29
0

You want to retain the first two associative elements, so you can make array_slice() calls within array_map(). (Demo)

var_export(
    array_map(fn($row) => array_slice($row, 0, 2), $array)
);

Or mapped called of array_intersect_key() against an establish whitelist array. (Demo)

$keep = ['id' => '', 'name' => ''];
var_export(
    array_map(
        fn($row) => array_intersect_key($row, $keep),
        $array
    )
)

Or, you could use array destructuring inside of a classic foreach() and make iterated compact() calls. (Demo)

$result = [];
foreach ($array as ['id' => $id, 'name' => $name]) {
    $result[] = compact(['id', 'name']);
}
var_export($result);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
-1

If you want to edit the same array in place, you can simply iterate over them and unset them.

<?php 

$preserve_keys = ['id','name'];

foreach($arr as &$data){
    foreach($data as $key => $value){
        if(!in_array($key,$preserve_keys)){
            unset($data[$key]);
        }
    }
}

If you want it as a separate result, loop over and add it to the new array.

<?php

$new_result = [];

foreach($arr as $data){
    $new_result[] = [
        'id' => $data['id'],
        'name' => $data['name']
    ];
}

print_r($new_result);
nice_dev
  • 17,053
  • 2
  • 21
  • 35