Avatar of Lupi05
Lupi05 asked on

array_filter on multidimensional array in PHP

Hi experts,

I have a twodimensional array like so:

[widgetA][green][10.99]
[widgetB][black][11.99]
[widgetC][green][12.99]
[widgetD][black][13.99]
[widgetE][black][14.99]

The array uses numeric indexes, so

$myarray[3][2] would be "13.99" and $myarray[0][1] would be "green".

Now I want to use array_filter to only get the 2nd dimension arrays which are "black".
[widgetB][black][11.99]
[widgetD][black][13.99]
[widgetE][black][14.99]

So what I need to do is check whether $myarray[x][1] == "black". And then check the whole array.

I can't wrap my head around the callback function for the array_filter... How do I check the array?

Thanks, Chris
PHP

Avatar of undefined
Last Comment
Lupi05

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
HuyBD

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
Lupi05

HuyBD, that's working, sweet, thanks a lot... Just one quick follow up question...

function filt($match)
{
if($match[1]=="black")
        return true;
else
        return false;
}
$ret=array_filter($my_array_thats_pulled_from_database,"filt");
print_r($ret);

In fact, what I didn't mention in my question is that the array contain strings like

[widgetA][this is a green house][10.99]
[widgetB][black cars are cool][11.99]
[widgetC][green ipods rock][12.99]

I still want to check for "black"... What's the easiest way to do this?

PHP functions to check strings? Or is there something for PHP as there is for SQL, where I could use something like "LIKE %black%"?

Thanks so much for your help. Cheers, Chris
HuyBD

you can try with stristr function to check
if(stristr($match[1],"black"))

Open in new window

HuyBD

e.g
function filt($match)
{
if(stristr($match[1],"black"))
        return true;
else
        return false;
}
$arr=array();
$arr[]=array("widgetA","green","10.99");
$arr[]=array("widgetB","black","11.99");
$ret=array_filter($arr,"filt");
print_r($ret);

Open in new window

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER
Lupi05

Perfect, thank you!