反向字母排序多维PHP数组维护密钥

时间:2023-01-27 21:34:23

I'm dying here, any help would be great.

我在这里死了,任何帮助都会很棒。

I've got an array that I can sort a-z on the value of a specific key but cannot sort in reverse z-a.

我有一个数组,我可以对特定键的值排序a-z但不能反向排序z-a。

sample of my array which i'd like to sort by ProjectName (z-a):

我希望按ProjectName(z-a)排序的数组样本:

Array
( 
 [0] => Array
    (
        [count] => 1
        [ProjectName] => bbcjob
        [Postcode] => 53.471922,-2.2996078
        [Sector] => Public

    )

[1] => Array
    (
        [count] => 1
        [ProjectName] => commercial enterprise zone
        [Postcode] => 53.3742081,-1.4926439
        [Sector] => Public

    )

[2] => Array
    (
        [count] => 1
        [ProjectName] => Monkeys eat chips
        [Postcode] => 51.5141492,-0.2271227
        [Sector] => Private

the desired results would be to maintain the entire array key -> value structure but with the order:

期望的结果是维护整个数组键 - >值结构但是顺序如下:

Monkeys eat chips
Commericial enterprise zone
bbcjob

猴子吃筹码商业企业区bbcjob

I hope this makes sense

我希望这是有道理的

1 个解决方案

#1


2  

This is a job for usort which lets you define a function to do your comparison and then sort the array based on that.

这是一个usort工作,它允许您定义一个函数来进行比较,然后根据它对数组进行排序。

function cmp($a, $b)
{
    return strcmp($b["ProjectName"], $a["ProjectName"]);
}

usort($yourArray, "cmp");

print_r($yourArray);

Edit: based on your comment, you should just reverse the $x and $y in your function to reverse the order of the sorting performed.

编辑:根据您的评论,您应该反转函数中的$ x和$ y以反转执行的排序顺序。

function name_sort($x, $y) 
{
    return strcasecmp($y['ProjectName'], $x['ProjectName']); 
}

#1


2  

This is a job for usort which lets you define a function to do your comparison and then sort the array based on that.

这是一个usort工作,它允许您定义一个函数来进行比较,然后根据它对数组进行排序。

function cmp($a, $b)
{
    return strcmp($b["ProjectName"], $a["ProjectName"]);
}

usort($yourArray, "cmp");

print_r($yourArray);

Edit: based on your comment, you should just reverse the $x and $y in your function to reverse the order of the sorting performed.

编辑:根据您的评论,您应该反转函数中的$ x和$ y以反转执行的排序顺序。

function name_sort($x, $y) 
{
    return strcasecmp($y['ProjectName'], $x['ProjectName']); 
}