Re: traversing multi-dimensional arrays

From: Date: Thu, 17 Feb 2005 16:56:30 +0000
Subject: Re: traversing multi-dimensional arrays
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-208929@lists.php.net to get a copy of this message
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


« previous php.general (#208929) next »