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]

Link to comment
Share on other sites

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')
);

Link to comment
Share on other sites

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";
    }
}

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.