我有以下数组:
$dish = [
'fr' => [
['lunch','starter','dish name fr 1','dish info 1','price 1'],
['lunch','starter','dish name fr 2','dish info 2','price 2'],
['both','starter','dish name fr 3','dish info 3','price 3'],
['both','main','dish name fr 4','dish info 4','price 4'],
['both','main','dish name fr 5','dish info 5','price 5'],
['both','main','dish name fr 6','dish info 6','price 6'],
['both','dessert','dish name fr 7','dish info 7','price 7'],
['diner','dessert','dish name fr 8','dish info 8','price 8'],
],
'nl' => [
['lunch','starter','dish name nl 1','dish info 1','price 1'],
['lunch','starter','dish name nl 2','dish info 2','price 2'],
['both','starter','dish name nl 3','dish info 3','price 3'],
['both','main','dish name nl 4','dish info 4','price 4'],
['both','main','dish name nl 5','dish info 5','price 5'],
['both','main','dish name nl 6','dish info 6','price 6'],
['both','dessert','dish name nl 7','dish info 7','price 7'],
['diner','dessert','dish name nl 8','dish info 8','price 8'],
],
'en' => [
['lunch','starter','dish name en 1','dish info 1','price 1'],
['lunch','starter','dish name en 2','dish info 2','price 2'],
['both','starter','dish name en 3','dish info 3','price 3'],
['both','main','dish name en 4','dish info 4','price 4'],
['both','main','dish name en 5','dish info 5','price 5'],
['both','main','dish name en 6','dish info 6','price 6'],
['both','dessert','dish name en 7','dish info 7','price 7'],
['diner','dessert','dish name en 8','dish info 8','price 8'],
],
];
与
foreach ($dish[$lang] as list($a, $b, $dish_name, $dish_info, $price)) {
echo $dish_name
; }
我设法通过语言:
菜名fr 1
菜名fr 2
菜名fr 3
菜名nl 1
菜名nl 2
菜名nl 3
菜名en 1
菜名en 2
菜名en 3
但我也想通过菜肴来展示:
初学者
菜名fr 1
菜名nl 1
菜名en 1
菜名fr 2
菜名nl 2
菜名en 2
菜名fr 3
菜名nl 3
菜名en 3
主要
菜名fr 4
菜名nl 4
菜名en 4
菜名fr 5
菜名nl 5
菜名en 5
菜名fr 3
菜名nl 3
菜名en 3
你会怎么做?
谢谢
答案 0 :(得分:0)
我会正确地将它重建为另一个数组:
$newArr = array();
$i = 0;
foreach($dish AS $langString => $lang){
foreach($lang AS $key => $subdish){
$newArr[$subdish[1]][$i]['dish'] = $subdish[2];
$newArr[$subdish[1]][$i]['sort'] = $key;
$i++;
}
}
function sortByOrder($a, $b) {
return $a['sort'] - $b['sort'];
}
usort($newArr['starter'], 'sortByOrder');
usort($newArr['main'], 'sortByOrder');
usort($newArr['dessert'], 'sortByOrder');
foreach($newArr as $course => $food){
echo '<h2>' . $course .'</h2>';
foreach($food as $plate){
echo $plate['dish'] . '<br />';
}
}
请记住,它可以更聪明,更有效地完成,这纯粹是为了给你一个&#39;了解如何实现这样的目标。
此外,您必须找到一种方法来对新阵列中的菜肴进行分类,以便按照您的方式进行排序。
<强>更新强>
添加了排序功能,是的,有很多代码可以说是简单的,但这是我当时可以酿造的,并且数据结构可用。