数组排序菜单



我有以下数组来显示基于用户指定顺序的菜单。

阵列如下:

$menuArray = [
'Main Street' => [
['/index.php', 'Home'],
['/city.php', $cityData[$user->city][0]],
['/travel.php', 'Travel'],
['/bank.php', 'Bank'],
['/inventory.php', 'Inventory'],
['/dailies.php', 'Dailies'],
],
'Activities' => [
(!$my->hospital) ? ['/hospital.php', 'Hospital'] : [],
(!$my->hospital && !$my->prison) ? ['/crime.php', 'Crime'] : [],
['/missions.php', 'Missions'],
['/achievements.php', 'Achievements'],
],
'Services' => [
['/hospital.php', 'Hospital'],
['/prison.php', 'Prison'],
['/search.php', 'Search'],
],
'Account' => [
['/edit_account.php', 'Edit Account'],
['/notepad.php', 'Notepad'],
['/logout.php', 'Logout'],
]
];

我在数据库中存储了一个列menu_order,它的默认值为0,1,2,3,4,但每个用户都可以更改,因为他们可以根据自己的喜好更改菜单。

我想实现的目标:

0 => Main Street
1 => Activities
2 => Services
3 => Account
4 => Communication

为了获得菜单订单,我做

$menuOrder = explode(',', $user->menu_order);

但是我不知道如何处理foreach来显示菜单。

这里有一种方法——使用替换而不是排序算法。

代码:(演示(

$menuArray = [
'Main Street' => [],
'Activities' => [],
'Services' => [],
'Account' => []
];
$lookup = [
0 => 'Main Street',
1 => 'Activities',
2 => 'Services',
3 => 'Account',
4 => 'Communication'
];
$customsort = '4,2,1,3,0';
$keys = array_flip(explode(',', $customsort));  convert string to keyed array
//var_export($keys);
$ordered_keys = array_flip(array_replace($keys, $lookup));  // apply $lookup values to keys, then invert key-value relationship
//var_export($ordered_keys);
$filtered_keys = array_intersect_key($ordered_keys, $menuArray);  // remove items not on the current menu ('Communication" in this case)
//var_export($filtered_keys);
$final = array_replace($filtered_keys, $menuArray);  // apply menu data to ordered&filtered keys
var_export($final);

输出:

array (
'Services' => 
array (
),
'Activities' => 
array (
),
'Account' => 
array (
),
'Main Street' => 
array (
),
)

这里有另一种使用uksort()和宇宙飞船操作员的方法:

$ordered_keys = array_flip(array_values(array_replace(array_flip(explode(',', $customsort)), $lookup)));
uksort($menuArray, function($a, $b) use ($ordered_keys) {
return $ordered_keys[$a] <=> $ordered_keys[$b];
});
var_export($menuArray);

由于您存储自定义排序顺序的方式,所涉及的大多数代码只是设置"映射"/"查找"数据。

您可以尝试这样的方法来生成菜单:

function display_menu($menus, $m) {
if (!isset($menus[$m])) return;
echo "<ul>";
foreach ($menus[$m] as $item) {
if (!count($item)) continue;
echo "<li><a href="{$item[0]}">{$item[1]}</a>n";
}
echo "</ul>";
}
$menuMap = array(0 => 'Main Street',
1 => 'Activities',
2 => 'Services',
3 => 'Account',
4 => 'Communication');
$menuOrder = explode(',', $user->menu_order);
foreach ($menuOrder as $menuIndex) {
$thisMenu = $menuMap[$menuIndex];
display_menu($menuArray, $thisMenu);
}

3v4l.org 上的小型演示

最新更新