[英]PHP array_multisort
I'm having some difficulties with sorting arrays.我在排序 arrays 时遇到了一些困难。 I tried with methods SORT_DESC, SORT_NUMERIC but it never works.我尝试了 SORT_DESC、SORT_NUMERIC 方法,但它从来没有用过。 Even when I put array_multisort anywhere else in the code.即使我将 array_multisort 放在代码中的其他任何位置。
So this is how my arrays looks like:所以这就是我的 arrays 的样子:
Array
(
[0] => Array
(
[0] => 0.13
[1] => Ships From
[2] => Russia
)
)
Array
(
[0] => Array
(
[0] => 0.11
[1] => Color
[2] => Green
)
)
Array
(
[0] => Array
(
[0] => 0.1
[1] => Size
[2] => M
)
)
Array
(
[0] => Array
(
[0] => 0.12
[1] => Material
[2] => Flex
)
)
Array
(
[0] => Array
(
[0] => 0.13
[1] => Ships From
[2] => China
)
)
Array
(
[0] => Array
(
[0] => 0.11
[1] => Color
[2] => Red
)
)
Array
(
[0] => Array
(
[0] => 0.1
[1] => Size
[2] => L
)
)
Array
(
[0] => Array
(
[0] => 0.12
[1] => Material
[2] => Cotton
)
)
As you can see I have double [0], and by that value to sort them all.如您所见,我有双 [0],并按该值对它们进行排序。 So my code looks like this:所以我的代码如下所示:
foreach($value['options'] as $key => $option)
{
$sort = array();
$attribude= $this->attribute($option['key']);
$attribute_value= $this->attribude($getAttr->id, $option['value']);
$collection = array_push($sort, array($attribude->default_order, $attribude->label, $attribute_value->value));
print_r($sort);
}
I tried to add array_multisort($sort, SORT_ASC);
我试图添加array_multisort($sort, SORT_ASC);
basically everywhere where I could, but it's never working.基本上我可以在任何地方,但它从来没有工作过。 Any ideas how to solve that?任何想法如何解决这个问题?
I would suggest, if you can, restructuring your array before attempting to sort.我建议,如果可以的话,在尝试排序之前重组你的数组。 Below is an example of the restructured array sorted by the number 2 index.下面是一个按数字 2 索引排序的重组数组的示例。 You can adjust the index by changing this $row[2]
like $row[0]
to sort by the float value of index zero.您可以通过更改此$row[2]
来调整索引,如$row[0]
以按索引零的浮点值排序。
$array = [
array(0.13,'Ships From','C'),
array(0.12,'Ships From','D'),
array(0.10,'Ships From','B'),
array(0.14,'Ships From','A'),
];
$a = array();
$b = array();
foreach ($array as $key => $row) {
$a[$key] = $row[2];
}
array_multisort($a, SORT_ASC, $array);
echo '<pre>';
print_r($array);
echo '</pre>';
Array
(
[0] => Array
(
[0] => 0.14
[1] => Ships From
[2] => A
)
[1] => Array
(
[0] => 0.1
[1] => Ships From
[2] => B
)
[2] => Array
(
[0] => 0.13
[1] => Ships From
[2] => C
)
[3] => Array
(
[0] => 0.12
[1] => Ships From
[2] => D
)
)
An inline solution:内联解决方案:
usort($array, function($a, $b) { return $a[0] <=> $b[0]; });
A flagship operator requires PHP 7+, otherwise compare manually.旗舰运营商需要PHP 7+,否则手动比较。 For reverse (DESC) order swap $a with $b.对于反向 (DESC) 订单交换 $a 与 $b。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.