Reply to Re: [PHP] traversing multi-dimensional arrays

Your name:

Reply:


Posted by Brent Baisley on 02/17/05 18:56

Forget about the $cars array. The array "key" in the $models array will
be your car list.

$cars=array("ford","chevy");
$models=array("ford"=>array("ranger","escape"),"chevy"=>array("malibu","
tahoe"));
//Loop through first level of array, getting car maker
foreach($models as $carmaker=>$models) {
//Loop through car models, paring up with maker
foreach($models as $model) {
echo $carmaker.'-'.$model.'<br />';
}
}

Another option, which isn't as readable, is to use implode instead of
the inner loop.
$cars=array("ford","chevy");
$models=array("ford"=>array("ranger","escape"),"chevy"=>array("malibu","
tahoe"));
foreach($models as $car=>$models) {
$pairing = $car.'-'.implode('<br />'.$car.'-',$models).'<br />';
echo $pairing;
}


On Feb 17, 2005, at 9:49 AM, blackwater dev wrote:

> Hello all,
>
> What is the best way to do this? I have two arrays:
>
> $cars=array("ford","chevy");
> $models=array("ford"=>array("ranger","escape"),"chevy"=>array("malibu",
> "tahoe"));
>
> then I need to traverse both arrays:
>
> foreach ($cars as $car){
> //now I need to get into the models array and echo out all of the
> models that
> //coincide with the specific car so it should print
> out ford-ranger
> //I basically want to do this but can't
> //how can I get into this second array without looping
> through the whole thing each time?
> foreach($cars[$car] as $model){
>
> }
>
> }
>
> Thanks!
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>
--
Brent Baisley
Systems Architect
Landover Associates, Inc.
Search & Advisory Services for Advanced Technology Environments
p: 212.759.6400/800.759.0577

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация