[英]Array sorting by values descending and sort index by ascending in php
I have an array pr($site_name_with_value)
looks like this.我有一个数组pr($site_name_with_value)
看起来像这样。 This is the result of two combine_array
.这是两个combine_array
的结果。
Array(
[Ashuganj PDB] => 720
[Bagherhat PGCB] => 720
[Banani_CO] => 720
[Barapukuria PGCB] => 784
[Barishal PGCB] => 780
[Benapole_CO] => 752
[Bogura RO] => 776
[Bogura_CO(IS)] => 784
)
I have tried this to expected output.我已经试过这个达到预期的输出。
$site_name_with_value_order = arsort($site_name_with_value);
foreach ($site_name_with_value_order as $key => $val) {
echo "$key = $val\n";
}
It returns an error message Invalid argument supplied for foreach()它返回一条错误消息为 foreach() 提供的参数无效
First I want to sort them by value descending order
.首先,我想按值descending order
对它们进行排序。 Second if the value is the same then order index by ascending
.其次,如果值相同, ascending
索引进行排序。
I want to get output looks like this.我想让输出看起来像这样。 But I don't know how to gain my expected output.但我不知道如何获得预期的输出。
Array(
[Bogura_CO(IS)] => 784
[Barapukuria PGCB] => 784
[Barishal PGCB] => 780
[Bogura RO] => 776
[Benapole_CO] => 752
[Ashuganj PDB] => 720
[Bagherhat PGCB] => 720
[Banani_CO] => 720
)
First of all, you've created an array with duplicate key which is not a valid way.首先,您创建了一个带有重复键的数组,这是无效的方法。 So when you try to sort the array by value with arsort()
- Sort an array in reverse order and maintain index association , but it will return different results for different php version.因此,当您尝试使用arsort()
按值对数组进行排序时 -以相反的顺序对数组进行排序并保持索引关联,但它会针对不同的 php 版本返回不同的结果。 See the DEMO看演示
$array = array(
'Ash' => 776,
'Bag' => 720,
'Ban' => 720,
'Bar' => 776,
'Bar' => 780,
'Ben' => 752,
'Bog' => 720,
'Bog' => 780,
'Bue' => 776,
);
arsort($array);
print_r($array);
There's no need to assign the没有必要分配
arsort($site_name_with_value);
in another variable because it will only return to 1. So just loop the在另一个变量中,因为它只会返回 1。所以只需循环
$site_name_with_value
instead.反而。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.