简体   繁体   English

PHP如何移动数组值的子集来执行类似asort的操作?

[英]PHP How do I shift subset of array values to do something like asort?

First off I am new to this site and it is a big help, so thanks in advance for the input. 首先,我是这个网站的新手,它对您有很大帮助,所以在此先感谢您的输入。

I am trying to shift a subset of array values after comparing them, like asort. 我正在尝试比较数组值后转移数组值的子集,例如asort。

Here is what I have: 这是我所拥有的:

$array[name] = "name";
$array[date] = "date";
$array[item1] = 7;
$array[item2] = 16;
$array[item3] = 3;
$array[item4] = 16;
$array[item5] = 2;
$array[item6] = 10;
$array[author] = "author";
$array[location] = "location';

I would like to sort the itemsN values by sorting the values so the values of "16" are at end of the subset, and the values other than "16" are at the beginning of the subset. 我想通过对值进行排序来对itemsN值进行排序,以使“ 16”的值位于子集的末尾,而除“ 16”之外的值位于子集的开头。

So after the sort I want to end up with: 所以排序之后,我想得出的结果是:

$array[name] = "name";
$array[date] = "date";
$array[item1] = 7;
$array[item2] = 3;
$array[item3] = 2;
$array[item4] = 10;
$array[item5] = 16;
$array[item6] = 16;
$array[author] = "author";
$array[location] = "location';

You mean you want to "sort an array in reverse order and maintain index association"? 您是说要“以相反的顺序对数组排序并保持索引关联”?

arsort($array)

Or if you don't care about maintaing key/value association: 或者,如果您不关心维护键/值的关联,请执行以下操作:

rsort($array)

The ArrayObject has an asort() method: ArrayObject具有asort()方法:

$array->asort();
foreach ($array as $key => $value) {
    echo $key . ' - ' . $value . "\n";
}

Outputs: 输出:

1 - 2
2 - 2 
3 - 1
4 - 1
5 - 1

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

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