Link to home
Start Free TrialLog in
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
ASKER CERTIFIED SOLUTION
Avatar of HuyBD
HuyBD
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Lupi05
Lupi05

ASKER

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
you can try with stristr function to check
if(stristr($match[1],"black"))

Open in new window

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

Avatar of Lupi05

ASKER

Perfect, thank you!