Multidimensional array help

Say i have an array like this one:

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

10 => array [ ... ]

]

How can i filter this array so that i keep structure but only have keys id and name and their values?

One way is to build a new array and copy the values you like

$newArray = [];

foreach($existingArray as $existingItem)
{
    $newItem['id'] = $existingItem['id'];
    $newItem['name'] = $existingItem['name'];

    $newArray[] = $newItem;
}

or without the use of a temporary variable:

$newArray = [];

foreach($existingArray as $existingItem)
{
    $newArray[] = [
        'id' => $existingItem['id'],
        'name' => $existingItem['name']
    ];
}
1 Like

Or you could do it this way ->
<?php

$myArray = [
   0 => [
       'id' => 1,
       'name' => 'John',
       'address' => '1313 Mockingbird Lane',
       'city' => 'NY'
   ],
    1 => [
        'id' => 2,
       'name' => 'Jill',
       'address' => '13 Monster Lane',
       'city' => 'Detroit'       
    ]
];


echo '<pre>' . print_r($myArray, 1) . "</pre>";

foreach ($myArray as $array) {
    $output[] = array_slice($array, 0, 2);   
}

echo "<pre>" . print_r($output, 1) . "</pre>";

That way if you array changes you just change the slice offset.

or filter it with a custom function

<?php

$myArray = [
   0 => [
       'id' => 1,
       'name' => 'John',
       'address' => '1313 Mockingbird Lane',
       'city' => 'NY'
   ],
    1 => [
        'id' => 2,
       'name' => 'Jill',
       'address' => '13 Monster Lane',
       'city' => 'Detroit'       
    ]
];

array_walk($myArray, function(&$item){ unset($item['address'], $item['city']); });
print_r($myArray);

/*

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => John
        )

    [1] => Array
        (
            [id] => 2
            [name] => Jill
        )

)
Sponsor our Newsletter | Privacy Policy | Terms of Service