Jump to content

Slightly complex multidimensional array issue


Omzy

Recommended Posts

Here is my Categories array:

 

 
$cats=array(
'decorations'=>array('Decorations', 'Asian Wedding Decorations'),
'flowers'=>array('Flowers', 'Asian Wedding Flowers'),
);

 

Currently I print this out to to a form on the page as follows:

 

foreach($cats as $index => $value)
{
echo '
  <input type="checkbox" name="selection[]" value="'.$index.'" id="'.$index.'" />
  <label for="'.$index.'">'.$value[0].'</label>
';
}

 

So this is all fine and dandy. Now I also have a Subcategories array, which uses the first element of its array to join with the Categories array:

 

 
$subcats=array(
'balloons'=>array('decorations', 'Balloons'),
'banners'=>array('decorations', 'Banners'),

'roses'=>array('flowers', 'Roses'),
'tulips'=>array('flowers', 'Tulips'),
);

 

So basically I would like to print out the subcategories of the parent category in square brackets, for example:

 

Decorations [balloons, Banners]

Flowers [Roses, Tulips]

That makes no sense. It would take a lot more processing to do it with that subcat array. Can you change the format of your $subcat array to this:

 

$subcats=array(
'decorations'=>array('Banners', 'Balloons'),
'flowers'=>array('Tulips', 'Roses')
);

 

Or if you need the lowercase keys:

$subcats=array(
'decorations'=>array('banners'=>'Banners', 'balloons'=>'Balloons'),
'flowers'=>array('yulips'=>'Tulips', 'roses'=>'Roses')
);

foreach($cats as $cat_index => $cat_value)
{
    //Display category
    echo "  <input type=\"checkbox\" name=\"selection[]\" value=\"{$cat_index}\" id=\"{$cat_index}\" />";
    echo "<label for=\"{$cat_index}\">{$cat_value[0]}</label><br />";

    //Display subcats for the current category
    foreach($subcats[$cat_index] as $subcat_value)
    {
        echo " - {$subcat_value}<br />\n";
    }
}

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.