Rory
Rory

Reputation: 838

Removing keys and values from nested arrays in PHP

I have the following PHP array, where some elements are repeated one in an outer array and once in an inner array:

        array(
            'content' =>
                array(
                    'car' => '1',
                    'house' => '2',
                    'name' => 'a_name',
                ),
            'restrictions' =>
                array(
                    'page_size' => 500,
                    'page_offset' => 0,
                ),
            'car' => '1',
            'house' => '2',
            'name' => 'a_partner_name',
            'criteria' => array(),
        );

I'd like to know how to do the following (maybe using array_walk_recursive)?

Removing an element from the array completely, for example, if I remove the 'car' element the resulting array would look like (note the 2 'car' elements in the array are both removed):

        array(
            'content' =>
                array(
                    'house' => '2',
                    'name' => 'a_name',
                ),
            'restrictions' =>
                array(
                    'page_size' => 500,
                    'page_offset' => 0,
                ),
            'house' => '2',
            'name' => 'a_partner_name',
            'criteria' => array(),
        );

Set a value for an element in the array, for example, if I change the 'car' elements value from '1' to '2', the resulting array would look like (note again its changed in 2 places):

         array(
            'content' =>
                array(
                    'car' => '2',
                    'house' => '2',
                    'name' => 'a_name',
                ),
            'restrictions' =>
                array(
                    'page_size' => 500,
                    'page_offset' => 0,
                ),
            'car' => '2',
            'house' => '2',
            'name' => 'a_partner_name',
            'criteria' => array(),
        );

Many thanks!

Upvotes: 0

Views: 404

Answers (1)

m02ph3u5
m02ph3u5

Reputation: 3161

Use references (&) to make things easier (although I wouldn't recommend such a structure) and unset for deletion.

$innerArray = ['car' => 'some value'];

$outerArray = [
    'content' => &$innerArray,
    'car' => &$innerArray['car']
];

// change car to '2'
$outerArray['car'] = '2';
// is the same as
$innerArray['car'] = '2';
// is the same as
$outerArray['content']['car'] = '2';

// you can use this for deletion
function removeRecursive(&$array, $elem){
    foreach ($array as $key => &$value) {
        if($key === $elem)
            unset($array[$key]);
        elseif ($value instanceof Traversable || is_array($value))
            removeRecursive($value, $elem);
    }
}

removeRecursive($outerArray, 'car');

Upvotes: 2

Related Questions