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
Share on other sites

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.

Link to comment
Share on other sites

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
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.