Jump to content

foreach() loop on multi-dimensional array


Omzy

Recommended Posts

Here is my multi-dimensional array:

 

 
$subcats=array(

'lighting-effects'=>array(
   'light-shows'=>array('Light Shows', 'Wedding Light Shows'),
   'sound-systems'=>array('Sound Systems', 'Wedding Sound Systems'),
   'visual-displays'=>array('Visual Displays', 'Wedding Visual Displays'),
   'fireworks-pyrotechnics'=>array('Fireworks/Pyrotechnics', 'Wedding Fireworks/Pyrotechnics'),
   'star-cloths'=>array('Star Cloths', 'Wedding Star Cloths'),
   'mist-generators'=>array('Mist Generators', 'Wedding Mist Generators'),
   'virtual-flames'=>array('Virtual Flames', 'Wedding Virtual Flames'),
   'confetti-canons'=>array('Confetti Cannons', 'Wedding Confetti Cannons'),
),
);

 

I want to run a foreach loop on the 'lighting-effects' array keys (light-shows, sound-systems, etc). Currently I do it like this:

 

 
foreach($subcats as $index1 => $value1)
{
   foreach($value1 as $index2 => $value2)
   {
   // processing here
   }
}

 

But I'm wondering if this is a long winded way of doing it/is there a quicker way?

Link to comment
https://forums.phpfreaks.com/topic/203902-foreach-loop-on-multi-dimensional-array/
Share on other sites

Does 

foreach ($subcats['lighting-effects'] as $category => $effects)...

do the trick?

 

I think you would benefit from learning how to better name your variables, so you could read http://www.objectmentor.com/resources/articles/naming.htm

That is perfectly reasonable, although I would give the variables more logical names.

 

dabaR's method would save a single step (save a nanosecond or two) but would give the code a more compact/logical display. However, it would not work if there are multiple main categories.

Well, there isn't going to be a "quicker" method, but depending on your needs you can create a function to return a single array with all the child values:

 

function allSubcategoryValues($multiArray)
{
    $outputArray = array();
    foreach ($multiArray as $subCat)
    {
        $outputArray = array_merge($outputArray, $subCat);
    }
    return $outputArray;
}

foreach(allSubcategoryValues($subcats) as $value)
{
    // processing here
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.