Reputation: 365
I'm seem to be stuck on something..
What I'm trying to do: with the following sample data I'm trying to show the data first in category and then show the data in the subcategory.
Sample Data:
array('category'=> 'America',
'sub-category'=> 'Illinois',
'name'=>'John Doe');
array('category'=>'America',
'sub-category'=>'Wisconsin',
'name'=>'Jane Doe');
Basically like this:
America
Illinois
John Doe
Wisconsin
Jane Doe
I can do the category by using the following code:
foreach ($total_states as $key => $states) {
$states_category[$states['CATEGORY']]['category'] = $states['CATEGORY'];
$statest_category[$states['CATEGORY']]['name'][] = $states;
}
How can I break it down by sub-categories using that for loop?
Upvotes: 0
Views: 142
Reputation: 1145
Give a try to this:
Initial data:
$info = [
['category' => 'America',
'sub-category' => 'Illinois',
'name' => 'John Doe'],
['category' => 'America',
'sub-category' => 'Wisconsin',
'name' => 'Jane Doe']];
Foreach:
foreach ( $info as $array ){
foreach ( $array as $key => $value){
switch ( $key ){
case 'category' : {
echo $value . '<br>';
break;
}
case 'sub-category' : {
echo " " . $value . '<br>';
break;
}
case 'name' : {
echo " " . $value . '<br>';
break;
}
}
}
}
Upvotes: 0
Reputation: 5039
I tested and come up with this code:
<?php
$datas = [
[
'category' => 'America',
'sub-category' => 'Illinois',
'name' => 'John Doe'
],
[
'category' => 'America',
'sub-category' => 'State',
'name' => 'John Doedf'
],
[
'category' => 'America',
'sub-category' => 'State',
'name' => 'ghghjgj Doe'
],
];
$newArray = [];
foreach($datas as $d)
$newArray[$d['category']][$d['sub-category']][] = $d['name'];
foreach($newArray as $country => $city) {
echo $country. '<br>';
foreach($city as $subcity => $users) {
echo "\t $subcity <br>";
foreach($users as $u)
echo "\t\t $u <br>";
}
}
Upvotes: 1