到目前为止,我已经尝试了一个带有内部foreach循环的foreach循环。这样可以很好地提取细节和回声,但是我不知道如何在foreach循环期间成功地对数据进行分组。
我目前有以下数组:
Array
(
[group] => Array
{
[5] => group1-title
[6] => group2-title
}
[treatment] => Array
(
[5] => Array
(
[16] => Array
(
[title] => title1
[description] => description1
[price] => price1
)
[17] => Array
(
[title] => title2
[description] => description2
[price] => price2
)
[6] => Array
(
[21] => Array
(
[title] => title3
[description] => description3
[price] => price3
)
}
}
}
(在现实中,数组数据很大,所以它被裁剪为上面的例子)
我要做的是在数组上运行foreach循环,以使我能够将数据分组在价格表中,按其组(数组键[5]
和[6]
)分开
我想要的最终结果如下:
Group1-Title
Title 1 | Desc | Price
Title 2 | Desc | Price
Group2-Title
Title 3 | Desc | Price
到目前为止,我已经尝试了一个带有内部foreach循环的foreach循环。这样可以很好地提取细节和回声,但是我不知道如何在foreach循环期间成功地对数据进行分组。
这里有一种方法。获取第一个数组项并将其用于标题。然后使用第一项的键遍历数组的其余部分以显示结果。显然,我的显示代码是快速和肮脏的,但这应该让你开始。
foreach($your_array['group'] as $iGroupId => $sTitle) {
echo 'Group: ' . $sTitle . "n";
foreach($your_array['treatment'][$iGroupId] as $aGroup) {
echo implode('|', $aGroup); . "n"
}
}
$data = array(); //your data array above
//loop through the groups
foreach($data['group'] as $key=>$group){
//echo group header and table start
echo "<h1>$group</h1>";
echo "<table border=1>";
//loop through the data with the corresponding group key
foreach($data['treatment'][$key] as $row){
//echo row data
echo "<tr>";
echo "<td>{$row['title']}</td>";
echo "<td>{$row['description']}</td>";
echo "<td>{$row['price']}</td>";
echo "</tr>";
}
//close table.
echo "</table>";
}