繁体   English   中英

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

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

首先,我是这个网站的新手,它对您有很大帮助,所以在此先感谢您的输入。

我正在尝试比较数组值后转移数组值的子集,例如asort。

这是我所拥有的:

$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';

我想通过对值进行排序来对itemsN值进行排序,以使“ 16”的值位于子集的末尾,而除“ 16”之外的值位于子集的开头。

所以排序之后,我想得出的结果是:

$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';

您是说要“以相反的顺序对数组排序并保持索引关联”?

arsort($array)

或者,如果您不关心维护键/值的关联,请执行以下操作:

rsort($array)

ArrayObject具有asort()方法:

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

输出:

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

暂无
暂无

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

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