O.. O.. - 5 months ago 11
PHP Question

Filter 2D array by value of a particular key

How can I filter this array to only keep items with

[category] => 1
?

[0] => Array
(
[link] => index
[image] => spot
[category] => 0
)

[1] => Array
(
[link] => test
[image] => spotless
[category] => 0
)

[2] => Array
(
[link] => differentcat
[image] => spotly
[category] => 1
)

Answer

Use array_filter.

You want something like this (presuming you want to keep entries with category 1):

function categoryone($var)
{
    return (is_array($var) && $var['category'] == 1);
}

print_r(array_filter($your_array, "categoryone"));