Remove unwanted elements from subarrays in multidimensional array
Asked Answered
A

3

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?

Astir answered 27/3, 2020 at 13:19 Comment(4)
Do you actually need filtering (by some value) or are you looking to simply extract the two keys?Lanate
maybe the wrong term "filter" - what i'm lookng for is keeping only those 2 keys in that multidim arrayAstir
Loop and unset all other. or use array_columnCalandracalandria
A simple foreach where you build a new array would be the best choice if you also want to keep the original array intact.Lanate
S
4

Would this work?

$result = array_map(function($arr) {
    return [
        'id' => $arr['id'],
        'name' => $arr['name']
    ];
}, $orig_array);
Smoot answered 27/3, 2020 at 13:34 Comment(0)
A
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);
Amaro answered 7/2, 2022 at 14:25 Comment(0)
C
-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);
Calandracalandria answered 27/3, 2020 at 13:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.