David
David

Reputation: 509

PHP remove arrays by nested key value

I have some arrays that I'd like to unset based on a key.

For example, let's say I have this array:

$array = array(
  'one' => array('item' => '1'),
  'two' => array('item' => '2')
);

If I want to unset the nested array with key 'two', I could do:

unset($array['two'])

or if I wanted to unset just the item array for key 'two', I could do:

unset($array['two']['item'])

I want to dynamically delete array items based on known keys. So for example, I know I want to delete ['two']['item'].

How do I pass those two arguments to a method, that can then be appended to an array?

Example:

//This works fine if it's only the first item in the array
function deleteArray($keys)
{
  unset($this->array[$keys]);
}

But when we want to delete nested items, this would not work. I could pass in the keys as an array such as array('two', 'item') and build the index off of this, but not sure how....

Any help would be great! thank you!

Upvotes: 4

Views: 2143

Answers (3)

ocirocir
ocirocir

Reputation: 4048

Try with a recursive function:

function deleteArray(&$array, $keys) {
    if ( count($keys) == 1 )
       unset( $array[$keys[0]] );
    else
    {
       $k = array_shift($keys);
       deleteArray($array[$k],$keys); 
    }
}
deleteArray($this->arr, array("three","item","blabla")); // This erase $this->array["three"]["item"]["blabla"]

Upvotes: 1

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22152

You can use this function:

function delete(&$array, $keys)
{
   $key = array_shift($keys);

   if (count($keys) == 0)
      unset($array[$key]);
   else
      delete($array[$key], $keys);
}

Upvotes: 6

Dion
Dion

Reputation: 3335

function deleteArray($keys)
{
$keyarray = explode($keys, " ");
   unset($this->array[$keyarray[0]][$keyarray[1]]);
}

I edited it a bit (won't work!) maybe somebody could continue that. Maybe it is possible with a while() ...

Upvotes: 0

Related Questions