ANYBODY知道如何对多维数组进行排序吗?!我一直试图这样做几个小时,没有成功。我正在尝试按“升序”排序数组“$ page”,因为这是在导航栏中显示的位置。任何帮助将非常感激!已经尝试过文档中的大多数示例,但似乎没有任何效果。
Array
(
[0] => Array
(
[position] => 0
[text] => Home
[url] => ./
[navigation] => true
)
[1] => Array
(
[position] => 0
[text] => 404
[url] => ./?p=404
[navigation] => false
)
[2] => Array
(
[position] => 0
[text] => 403
[url] => ./?p=403
[navigation] => false
)
[3] => Array
(
[position] => 1
[text] => Posts
[url] => ./?p=posts
[navigation] => true
)
[4] => Array
(
[position] => 3
[text] => Users
[url] => ./?p=users
[navigation] => true
)
[5] => Array
(
[position] => 1
[text] => Logout
[url] => ./?p=logout
[navigation] => false
)
[6] => Array
(
[position] => 2
[text] => Banner
[url] => ./?p=banner
[navigation] => true
)
[7] => Array
(
[position] => 5
[text] => Login
[url] => ./?p=login
[navigation] => false
)
)
请不要告诉我搜索,因为我有,但没有任何工作!当我在本地测试它时,其中一个确实工作,但我的服务器抛出了一个错误,所以我不得不找到一个替代方案。
答案 0 :(得分:2)
使用usort。
function cmp($a, $b)
{
if ($a['position'] == $b['position']) {
return 0;
}
return ($a['position'] < $b['position']) ? -1 : 1;
}
usort($page, "cmp");
答案 1 :(得分:0)
您可以在此处试用以下代码:sandbox
<强>代码强>
function intComparator($key) {
return function ($a, $b) use ($key) {
if ($a[$key] == $b[$key]) return 0;
return $a[$key] > $b[$key] ? 1 : -1;
};
}
$items = Array (
Array (
'position' => 0,
'text' => 'Home',
'url' => './',
'navigation' => True
),
Array (
'position' => 0,
'text' => '404',
'url' => './?p=404',
'navigation' => False
),
Array (
'position' => 0,
'text' => '403',
'url' => './?p=403',
'navigation' => False
),
Array (
'position' => 1,
'text' => 'Posts',
'url' => './?p=posts',
'navigation' => True
),
Array (
'position' => 3,
'text' => 'Users',
'url' => './?p=users',
'navigation' => True
),
Array (
'position' => 1,
'text' => 'Logout',
'url' => './?p=logout',
'navigation' => False
),
Array (
'position' => 2,
'text' => 'Banner',
'url' => './?p=banner',
'navigation' => True
),
Array (
'position' => 5,
'text' => 'Login',
'url' => './?p=login',
'navigation' => False
)
);
usort($items, intComparator('position'));
for ($i = 0; $i < count($items); $i++) {
echo "######## Item $i ########\n";
$item = $items[$i];
foreach($item as $key => $value) {
printf("%-12s=> %s\n", $key, $value);
}
}
<强>输出强>
######## Item 0 ########
position => 0
text => Home
url => ./
navigation => 1
######## Item 1 ########
position => 0
text => 403
url => ./?p=403
navigation =>
######## Item 2 ########
position => 0
text => 404
url => ./?p=404
navigation =>
######## Item 3 ########
position => 1
text => Logout
url => ./?p=logout
navigation =>
######## Item 4 ########
position => 1
text => Posts
url => ./?p=posts
navigation => 1
######## Item 5 ########
position => 2
text => Banner
url => ./?p=banner
navigation => 1
######## Item 6 ########
position => 3
text => Users
url => ./?p=users
navigation => 1
######## Item 7 ########
position => 5
text => Login
url => ./?p=login
navigation =>