Leachim wrote:Hi there. I have an array like this:
Code: Select all
$cats = array(array(
'cat_id' => '1',
'cat_name' => 'test',
'cat_subs' => array('cat_id' => '2', 'cat_name' => 'test2'), array('cat_id' => '3', 'cat_name' => 'test3'), array('cat_id' => '4', 'cat_name' => 'test4'))
);
Why not try something like this:
Code: Select all
$cats = array(
'1' => 'test',
'subs' => array(
'2' => 'test2',
'3' => 'test3',
'4' => 'test4'
)
);
Now if you would like to access the subs, simply:
Code: Select all
foreach($cats['subs'] as $sub_id => $sub_name)
{
echo "Sub $sub_id is called $sub_name.\n";
}
By using this approach you save yourself one level of leaves on the array-tree and a bit of headache in accessing them. I decided that since you are essentially using only two values for each main category with the ability of having multiple sub-categories attached to each category, why not combine the two "cat_id" and "cat_name" attributes into a key,value pair. Then we can follow suit and do the same for each of your sub categories.
If you find that you need to extend this into another tier to support multiple top categories, you could do so easily by wrapping the main categories in their own arrays, again, using the key,value notation:
Code: Select all
$cats = array(
'1' => array(
'name' => 'test',
'subs' => array(
'2' => 'test2',
'3' => 'test3',
'4' => 'test4'
)
),
'2' => array(
'name' => 'test2',
'subs' => array(
'5' => 'test5',
'6' => 'test6',
'7' => 'test7'
)
)
);
-Andy