Aivan Monceller
Aivan Monceller

Reputation: 4670

PHP filter 2 dimensional array by specific key

I have this array:

Array
(
    [702a4584] => Array
        (
            [type] => folder
            [id] => 702a4584
        )

    [b547b3a9] => Array
        (
            [type] => folder
            [id] => b547b3a9

        )

    [fcb0d055] => Array
        (
            [type] => page
            [id] => fcb0d055
        )
)

I want to filter the array such that only type "folder" will remain:

Array
(
    [702a4584] => Array
        (
            [type] => folder
            [id] => 702a4584
        )

    [b547b3a9] => Array
        (
            [type] => folder
            [id] => b547b3a9

        )

)

I could do this, but I'll be needing a generic function:

$temp = array();
foreach($array as $key => $value)
{
    if($value['type'] =="folder")
    {
        $temp[$key] = $value; 
    }
}

Upvotes: 3

Views: 10715

Answers (3)

Jorge Mauricio
Jorge Mauricio

Reputation: 533

I encountered a strange situation that might be useful to add here for someone in the future, since when I was searching for it, it pointed to this post.

I´m using Laravel and when I dumped @dump($myData) my 2 dimensional array, it was showing as array inside arrays. However, my filter_array logic wasn´t working.

After hours trying to debug it, I used old school var_dump($myData) and found out that the inner array wasnt´s an array - it had been converted for some reason into an object. And it was returning me the following error: Cannot use object of type stdClass as array.

Struggled a a bit more until I came up with two alternatives:

Assume the object:

$filteredArray = array_filter($originalArray, function ($arr) {
    return $arr->id_filter_index === 101; // Working. For some reason, the $arr is an object.
});

Force array conversion:

$filteredArray = array_filter($originalArray, function ($arr) {
    $arr = json_decode(json_encode($arr), true); // Force converting to array.
    return $arr['id_filter_index'] === 101;
});

BTW: the $originalArray was filtered also and not sure why the inner arrays became objects. If anyone has context about it, leave it in the comments. Hope this saves valuable debugging time for anyone out there.

Upvotes: 0

chanchal
chanchal

Reputation: 594

$input = Array(1,2,3,1,2,3,4,5,6);
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));

Upvotes: -1

mfonda
mfonda

Reputation: 8003

You could use array_filter:

$filtered = array_filter($array, function($v) { return $v['type'] == 'folder'; });

Upvotes: 20

Related Questions