我似乎被困在某事上......
我正在尝试做什么:使用以下示例数据,我试图首先在类别中显示数据,然后在子类别中显示数据。
示例数据:
array('category'=> 'America',
'sub-category'=> 'Illinois',
'name'=>'John Doe');
array('category'=>'America',
'sub-category'=>'Wisconsin',
'name'=>'Jane Doe');
基本上是这样的:
America
Illinois
John Doe
Wisconsin
Jane Doe
我可以使用以下代码执行该类别:
foreach ($total_states as $key => $states) {
$states_category[$states['CATEGORY']]['category'] = $states['CATEGORY'];
$statest_category[$states['CATEGORY']]['name'][] = $states;
}
如何使用for循环按子类划分?
答案 0 :(得分:1)
我测试并提出了这段代码:
<?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>";
}
}
答案 1 :(得分:0)
尝试一下:
初始数据:
$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;
}
}
}
}