Removing a parent in a multidimensional PHP array

What is the best way to remove the parent of the associated key in a multidimensional array? For example, suppose we have the following array, and I want to find "[text] = a" and then delete its parent array [0] ...

(array) Array
(

[0] => Array
    (
        [text] => a
        [height] => 30
    )

[1] => Array
    (
        [text] => k
        [height] => 30
    )
)
+5
source share
5 answers

Here is the obvious:

foreach ($array as $key => $item) {
    if ($item['text'] === 'a') {
        unset($array[$key]);
    }
}
+6
source

Internal arrays do not support references to their "parent" arrays, so you will have to write a function to manually track this. Maybe something like this:

function searchAndDestroy(&$arr, $needle) {
    foreach ($arr as &$item) {
        if (is_array($item)) {
            if (searchAndDestroy($item, $needle)) {
                return true;
            }
        } else if ($item === $needle) {
            $item = null;
            return true;
        }
    }
}

, , , , , .

+2

array_filter:

function filter_callback($v) {
  return !isset($v['text']) || $v['text'] !== 'a';
}
$array = array_filter($array, 'filter_callback');

this will leave only the “parent elements” in the array, where text != a, therefore, removing those where the text is equal

+2
source

My implementation:

function searchAndDestroy(&$a, $key, $val){
    foreach($a as $k => &$v){
        if(is_array($v)){
            $r = searchAndDestroy(&$v, $key, $val);
            if($r){
                unset($a[$k]);
            }
        }elseif($key == $k && $val == $v){
            return true;
        }
    }
    return false;
}

searchAndDestroy($arr, 'text', 'a');

To check this:

<pre><?php

function searchAndDestroy(&$a, $key, $val){
    foreach($a as $k => &$v){
        if(is_array($v)){
            $r = searchAndDestroy(&$v, $key, $val);
            if($r){
                unset($a[$k]);
            }
        }elseif($key == $k && $val == $v){
            return true;
        }
    }
    return false;
}

$arr = array(array('text'=>'a','height'=>'30'),array('text'=>'k','height'=>array('text'=>'a','height'=>'20')));

var_dump($arr);

searchAndDestroy($arr, 'text', 'a');

var_dump($arr);

?></pre>

This function is recursive.

0
source

A simple and safe solution (I would not delete / delete elements from the array that I iterate over) could be:

$new_array = array();
foreach($array as $item)
{
    if($item['text'] != "a")
    {
        $new_array[] = $item;
    }
}
0
source

All Articles