简体   繁体   English

在foreach中按值对多维数组进行排序

[英]Sort Multi-dimensional Array by Value in foreach

Hi, 你好

I have a function like this: 我有一个这样的功能:

function column_links() {
 $column = scandir("content");
 foreach ($column as $value) {
    $stvalue = str_replace(".php", "", $value);
    echo "<a href=\"{$stvalue}\">{$GLOBALS['tags'][$stvalue][title]}</a>";
 }
}

and this is my variable: 这是我的变量:

define('title', 0);
define('desc', 1);
define('order', 2);

$tags = array(
    'index'    => array('My Page', 'this is a description', '1'),
    'about'    => array('About', 'this is a description', '2'),
    'sitemap'    => array('Site Map', 'this is a description', '3'));  

I want to sort the produced links by "order" rather than by file name so my html would look like this: 我想按“顺序”而不是文件名对产生的链接进行排序,因此我的html如下所示:

<a href="index">My Page</a>
<a href="about">About</a>
<a href="sitemap">Site Map</a>

I thought that array_multisort would do the trick but I cant even figure out where to put it. 我以为array_multisort可以解决问题,但我什至不知道该放在哪里。 Any ideas please? 有什么想法吗?

Thank you. 谢谢。

You can use the array function usort to define your own sorts! 您可以使用数组函数usort定义自己的排序!

The way it works is that you write your own function to determine how the array should be sorted. 它的工作方式是您编写自己的函数来确定应如何对数组进行排序。 The function should return an integer less than, equal to, or greater than zero to determine how the first argument compares to the second. 该函数应返回小于,等于或大于零的整数,以确定第一个参数与第二个参数的比较方式。

For example: 例如:

I write a custom function called order_sort , which compares the ['order'] keys. 我编写了一个自定义函数order_sort ,它比较['order']键。

function order_sort($a, $b) {
    if ($a['order'] > $b['order'])
        return 1;
    if ($a['order'] < $b['order'])
        return -1;
    return 0;
}

Then I can call usort on my array to sort it using my custom function. 然后,我可以使用自定义函数在数组上调用usort对其进行排序。

usort($tags, 'order_sort');

Its keys will be discarded and the arrays will be sorted by ['order'] . 它的键将被丢弃,数组将按['order']排序。

Your code is a little confusing, I hope I understood your example right. 您的代码有些混乱,我希望我理解您的示例正确。 If not, I hope my example helped you write your own! 如果没有,我希望我的例子可以帮助您编写自己的例子!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM