通过多维数组PHP的特定键排序

时间:2021-12-21 01:16:59

I have an array of arrays. The inner array looks like this.

我有一个数组数组。内部数组看起来像这样。

 Array
    (
        [comparisonFeatureId] => 1188
        [comparisonFeatureType] => Category
        [comparisonValues] => Array
            (
                [0] => Not Available
                [1] => Not Available
                [2] => Not Available
                [3] => Standard
            )

        [featureDescription] => Rear Reading Lamps
        [groupHeader] => Convenience
    )

So I have an array of the above array and I need to sort the array by featureDescription. Is there a way to do this using one of PHPs internal functions?

所以我有一个上面数组的数组,我需要通过featureDescription对数组进行排序。有没有办法使用PHP的内部函数之一?

2 个解决方案

#1


2  

See a list of all of PHP's sorting functions here: http://php.net/manual/en/array.sorting.php

在这里查看所有PHP的排序函数列表:http://php.net/manual/en/array.sorting.php

You probably want usort().

你可能想要usort()。

<?php

function myCmp($a, $b)
{
  return strcmp($a["featureDescription"], $b["featureDescription"]);
}

usort($myArray, "myCmp");

#2


1  

One way would be to use the array_multisort function. The only downside to this is that you require a copy of all the featureDescription values (with a quick foreach for a example) from your array's first level.

一种方法是使用array_multisort函数。唯一的缺点是,您需要从阵列的第一级获得所有featureDescription值的副本(以示例的快速foreach为例)。

$featureDescriptionValues = array();    
foreach ($myArray as $node)
{
    $featureDescriptionValues[] = $node['featureDescription'];
}

array_multisort($myArray, $featureDescriptionValues, SORT_STRING, SORT_ASC);

It is important that the $featureDescriptionValues appear in the same order as they are represented in $myArray.

重要的是$ featureDescriptionValues的显示顺序与$ myArray中表示的顺序相同。

#1


2  

See a list of all of PHP's sorting functions here: http://php.net/manual/en/array.sorting.php

在这里查看所有PHP的排序函数列表:http://php.net/manual/en/array.sorting.php

You probably want usort().

你可能想要usort()。

<?php

function myCmp($a, $b)
{
  return strcmp($a["featureDescription"], $b["featureDescription"]);
}

usort($myArray, "myCmp");

#2


1  

One way would be to use the array_multisort function. The only downside to this is that you require a copy of all the featureDescription values (with a quick foreach for a example) from your array's first level.

一种方法是使用array_multisort函数。唯一的缺点是,您需要从阵列的第一级获得所有featureDescription值的副本(以示例的快速foreach为例)。

$featureDescriptionValues = array();    
foreach ($myArray as $node)
{
    $featureDescriptionValues[] = $node['featureDescription'];
}

array_multisort($myArray, $featureDescriptionValues, SORT_STRING, SORT_ASC);

It is important that the $featureDescriptionValues appear in the same order as they are represented in $myArray.

重要的是$ featureDescriptionValues的显示顺序与$ myArray中表示的顺序相同。