easyedy Posted January 11, 2008 Share Posted January 11, 2008 Hi I'm trying to filter my multidimensional array based of the ID passed. I'm almost there but I missed a step somewhere. Here is the code below when I try to filter the array by ID =1 ie: product.php?id=1 Array ( [brand] => Array ( [Type] => Array ( [0] => Array ( [iD] => 1 [Name] => Plus [size] => XL [Price] => 100 ) [1] => Array ( [iD] => 3 [Name] => Shox [size] => XL [Price] => 100 ) [2] => Array ( [iD] => 2 [Name] => Zoom [size] => XL [Price] => 100 ) [3] => Array ( [iD] => 1 [Name] => Plus [size] => XL [Price] => 100 ) ) ) ) function array_filter_multi($input, $filter="", $keepMatches=true) { if (!is_array($input)) return ($input==$filter xor $keepMatches==false) ? $input : false; while (list ($key,$value) = @each($input)){ $res = array_filter_multi($value, $filter,$keepMatches); if ($res !== false) $out[$key] = $res; } return $out; } $newArray = array_filter_multi($result['Brand']['Type'], $filter= $_GET[id], $keepMatches=true); print_r($newArray); Gives me the output of: Array ( [0] => Array ( [iD] => 1 ) [1] => Array ( [iD] => 1 ) ) It's just giving me the ID's and not the full array with ID, Name, Size, & Price... Any thoughts? Thx Quote Link to comment https://forums.phpfreaks.com/topic/85555-solved-filter-values-in-multidimensional-array/ Share on other sites More sharing options...
GingerRobot Posted January 11, 2008 Share Posted January 11, 2008 Well, without your code, its pretty difficult to tell you whats wrong with it. However, i put this together which i think will do what you're after (and possibly more): <?php $array = array('Brand'=>array('Type'=>array(array('ID'=>1,'Name'=>'Plus','Size'=>'XL','Price'=>100),array('ID'=>3,'Name'=>'Shox','Size'=>'XL','Price'=>100)))); function find_items($array,$findwhat,$value,$found=array()){ foreach($array as $k=>$v){ if(is_array($v)){ $result = find_items($v,$findwhat,$value,$found); if($result === true){ $found[] = $v; }else{ $found = $result; } }else{ if($k==$findwhat && $v==$value){ return TRUE; } } } return $found; } $found = find_items($array,'ID',1); echo '<pre>'.print_r($found,1).'</pre>'; ?> This will allow you to search for any product where the attribute matches what you're after. So, in the above example, we can search for a product where the ID is 1. Or, we could search for all products where the size is XL, using: $found = find_items($array,'ID',1); echo '<pre>'.print_r($found,1).'</pre>'; If this isn't what you want, please explain a bit more fully. And post up the code you've got currently. Quote Link to comment https://forums.phpfreaks.com/topic/85555-solved-filter-values-in-multidimensional-array/#findComment-436709 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.