[thelist] Filtering an array in PHP for multiple criteria

Matt McKeon matt at camadro.com
Wed Jun 11 11:49:05 CDT 2008


Aaron Vegh wrote:
> Hi all,
> I've been breaking my brain on this problem for a while now, so I'm
> hoping there's some smarter PHP devs on this list than myself! That
> shouldn't be too hard. :-P
> 
> Assuming an array like this:
> 
> Array {
>     [0] Object {
>          category => "Workboot"
>          toe => "Steel"
>     }
> 
>     [1] Object {
>         category => "Workboot"
>         toe => "Aluminum"
>     }
> 
>     [2] Object {
>         category => "Athletic"
>         toe => "Steel"
>     }
> 
> The user has to choose from a number of criteria. If they choose the
> Workboot category and Steel toe, then the result array should contain
> only the first object in the array above. How the heck do you write a
> function that would do that??? Owing to the way the database and
> application are set up, I can't pull the results from the database
> using SQL; I have to get the entire catalogue out of the database, and
> then filter the results as they appear in this array. Any thoughts or
> pointers would be received gratefully. :-)
> 
> Thanks!
> Aaron.
> 
> 

Have you tried just looping through that array and doing a test on 
category and toe values? ie)

$usersCat = SOME_VALUE;
$usersToe = SOME_VALUE;
$resuls   = array();

for($i = 0, $c = count($catalog); $i < $c; $i++) {
   if($catalog[$i]['category'] == $usersCat && $catalog[$i]['toe'] == 
$usersToe) {
      $results = $catalog[$i];
   }
}

I don't know the size of your data set, but that could be an option (not 
tested). There are plenty of helpful array functions too 
<http://us.php.net/manual/en/ref.array.php>.

HTH

Matt



More information about the thelist mailing list