Ahmed
Ahmed

Reputation: 1533

PHP Multidimensional Array search where key equals and return main key

I have an array in php that looks like the following structure:

[0] => Array
    (
        [id] => 1242
        [name] => John
        [archived] => 
    )


[1] => Array
    (
        [id] => 1343
        [name] => Ben
        [archived] => 1 
    )


[2] => Array
    (
        [id] => 1149
        [name] => Mark
        [archived] => 
    )

Is there a way I can search for and unset the entire array element of the main key where archived equals 1? So for example in this data example the key 1 has a sub-key called archived equals 1 and hence the entire array element for key 1 can be unset?

Upvotes: 1

Views: 119

Answers (3)

gogaz
gogaz

Reputation: 2400

You can use array_filter to create a new array from your data:

$data = [['id' => 1, 'data' => 42, 'archived' => false],
         ['id' => 2, 'data' => 43, 'archived' => true]];
$filtered = array_filter($data, function ($var){ return !$var['archived'];});

Upvotes: 0

Maksym Fedorov
Maksym Fedorov

Reputation: 6456

You can use array_filter to create new array that wiil satisfies your contidional, for example:

$items = array_filter($arr, function($value, $key) {
    return $value['archived'] !== 1
}, ARRAY_FILTER_USE_BOTH);

Upvotes: 1

atoms
atoms

Reputation: 3093

This should work. Note that the unset is called on the original array, not $aInner!

$aArray = array(
    0 => array('id' => 1242, 'name' = "John", 'archived' => 1),
    1 => array('id' => 1342, 'name' = "Ben", 'archived' => 0)
);

// loop over each element in the array, if its set using the current iPos, unset the key from array
foreach ($aArray as $iPos => $aInner) {
    if($aInner['archived'] === 1){
        unset($aArray[$iPos]);
        continue;        
    }
}

Upvotes: 1

Related Questions