Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Parent in PHP Multidimensional Array

What's the best way to remove the parent of a matched key in an Multidimensional Array? For example, let's assume 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
    )
)
like image 689
Andres Avatar asked Mar 07 '10 10:03

Andres


People also ask

What is array_ keys() used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

What is array_ column?

The array_column() function returns the values from a single column in the input array.

How to get keys from an array PHP?

array_keys() returns the keys, numeric and string, from the array . If a search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.


2 Answers

Here’s the obvious:

foreach ($array as $key => $item) {
    if ($item['text'] === 'a') {
        unset($array[$key]);
    }
}
like image 161
Gumbo Avatar answered Sep 18 '22 18:09

Gumbo


using array_filter:

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

this will only leave 'parent elements' in the array where text != a, therefore deleting those where text equals a

like image 32
knittl Avatar answered Sep 20 '22 18:09

knittl