Page 1 of 1
Tripple array help
Posted: Thu Nov 06, 2008 2:02 pm
by Leachim
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'))
);
And I need to list all arrays in cat_subs. If I have more than one array in cat_subs and I use
I get values of first array. When I use this code
Code: Select all
$cats[0]['cat_subs'][$i]['cat_name']
I get nothing. ($i is an number)
So how to list arrays in the cat_subs?
Ty
Re: Tripple array help
Posted: Thu Nov 06, 2008 3:18 pm
by andyhoneycutt
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
Re: Tripple array help
Posted: Sat Nov 08, 2008 7:41 am
by Leachim
This not solved my problem. I have 7 main categories and each main cat has 5-10 sub categories, some main cast are without subcats. That array was only example, original array has more keys.. Like item count, description.... All data are from mysql.
Ok, I solved it... My array is like:
Code: Select all
$cats = array(array(
'cat_id' => '1',
'cat_name' => 'test',
'cat_subs' => array(array('cat_id' => '2', 'cat_name' => 'test2'), array('cat_id' => '3', 'cat_name' => 'test3'), array('cat_id' => '4', 'cat_name' => 'test4')))
);
And listing:
Code: Select all
$cats[$i]['cat_subs'][$j]['cat_name']
Re: Tripple array help
Posted: Wed Nov 19, 2008 10:53 am
by andyhoneycutt
Very good, glad you were able to solve it
-Andy