PHP按子键排序多维数组



我看了很多与此相关的线程,没有一个对我有任何帮助。我有一个数组,它遵循$array[location][store][person] = funds的基本结构。排序数组的最有效方法是什么,以便[人]键按ASC顺序?

现在的样子:

Array
(
    [Florida] => Array
        (
            [AppleSauce] => Array
                (
                    [Rabbit, Hunting] => 5
                    [Brown, Bubba] => 20
                    [Chicken, Cantina] => 10
                    [Gum, Bubble] => 10
                    [Pool, Swimming] => 4
                    [Bath, Taka] => 2
                )
        )
    [Texas] => Array
        (
            [BeatleJuice] => Array
                (
                    [Chicken, Cantina] => 10
                    [Pool, Swimming] => 4
                    [House, Road] => 5
                )
            [CaramelApple] => Array
                (
                    [Chicken, Cantina] => 10
                    [Pool, Swimming] => 4
                    [House, Road] => 5
                )
        )

这就是我要找的:

Array
    (
        [Florida] => Array
            (
                [AppleSauce] => Array
                    (
                        [Bath, Taka] => 2
                        [Brown, Bubba] => 20
                        [Chicken, Cantina] => 10
                        [Gum, Bubble] => 10
                        [Pool, Swimming] => 4
                        [Rabbit, Hunting] => 5
                    )
            )
        [Texas] => Array
            (
                [BeatleJuice] => Array
                    (
                        [Chicken, Cantina] => 10
                        [House, Road] => 5
                        [Pool, Swimming] => 4
                    )
                [CaramelApple] => Array
                    (
                        [Chicken, Cantina] => 10
                        [House, Road] => 5
                        [Pool, Swimming] => 4
                    )
            )

您可以使用ksort按字母顺序对人员的数组键进行排序

foreach($array as $state => $locations) {
    foreach($locations as $location => $people) {
        ksort($array[$state][$location]);
    }
}

php函数array_multisort可以这样做:

多维数组排序

<?php
$ar = array(
       array("10", 11, 100, 100, "a"),
       array(   1,  2, "2",   3,   1)
      );
array_multisort($ar[0], SORT_ASC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

在这个例子中,排序后,第一个数组将转换为"10",100,100,11,"a"(它是按升序排序的字符串)。第二个将包含1,3,"2",2,1(按数字降序排序)。

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1]=> int(100)
    [2]=> int(100)
    [3]=> int(11)
    [4]=> string(1) "a"
  }
  [1]=> array(5) {
    [0]=> int(1)
    [1]=> int(3)
    [2]=> string(1) "2"
    [3]=> int(2)
    [4]=> int(1)
  }
}

这是基于官方文档:

http://php.net/manual/en/function.array-multisort.php

相关内容

  • 没有找到相关文章

最新更新