【发布时间】:2019-02-28 11:34:47
【问题描述】:
早上好,我对此感到震惊,但是,php 有超过 10 种方法来对数组进行排序,但我找不到一种按所需键动态排序的方法。
我不能设置一些类似 uksorts 的东西,因为它会被动态填充。我在前面使用 smarty(它没有数组排序功能),我正在尝试制作一个可调用的静态来在一个特定点上使用和打印排序数组。
我已经对其应用了一些逻辑,我认为它会是这样的。
聪明:
{assign var='key' value='category_id'}
{assign var='direction' value='normal'}
{assign var='sortedItem' value=''}
{foreach $object.prop item="item"}
{sortedItem = Class::arraySortBy($item, $key, $direction)}
<a href="{$item['link']}">
{$item['name']}
</a>
{foreach}
PHP:
public static function arraySortBy($elemGroup, $sortBy, $direction) {
if(is_object($elemGroup)){
$elemGroup = (array) $elemGroup;
}
if ($direction == 'normal') {
// here is where i want to sort the elemGroup array by the key i want, as the key is product_id and i want to sort by category_id
} else if ($direction == 'reverse'){
// here the same but in reverse order
} else {
error_log('Direction not properly set.');
}
return $elemGroup;
}
事实是我想重新排序对象 bu category_id,其次是 product_id IE:
itemA{product_id=1, category_id=1}
itemB{product_id=2, category_id=2}
itemC{product_id=3, category_id=1}
itemE{product_id=4, category_id=1}
itemD{product_id=5, category_id=2}
结果:
itemA
itemB
itemC
itemE
itemD
预期结果
itemA
itemC
itemE
itemB
itemD
有没有办法使用 PHP 排序函数来实现它,或者它必须是自定义的?
谢谢
【问题讨论】:
-
什么代码会产生结果?
-
“我不能设置像一些 uksorts 这样的东西,因为它会被动态填充。” - 你的意思是什么?
-
@splash58 没有重现结果的代码。结果是默认的...
-
@04FS 我的意思是,如果您必须对要排序的每个键进行自定义排序,这很乏味,我希望它可能是一些 php 内置函数,例如 ksort(array, assocKey , 方向),这很容易。