如何基于值对数组进行分组

时间:2019-06-27 15:41:42

标签: php arrays

我有一个多维数组,我想根据第二个键对其进行分组。

例如,我的数组输出如下:

Array
(
    [1] => Array
        (
            [1] => 48.083261120685
        )

    [2] => Array
        (
            [3] => 40.509258201058
        )

    [3] => Array
        (
            [2] => 38.262252939418
        )

    [4] => Array
        (
            [3] => 42.296571965113
        )

    [5] => Array
        (
            [3] => 4.5825756949558
        )

    [6] => Array
        (
            [3] => 186.7110066386
        )

    [7] => Array
        (
            [3] => 149.29835899969
        )

    [8] => Array
        (
            [2] => 47.053161424074
        )

    [9] => Array
        (
            [2] => 15.58845726812
        )

    [10] => Array
        (
            [2] => 6.164414002969
        )

    [11] => Array
        (
            [1] => 4.5825756949558
        )

    [12] => Array
        (
            [2] => 42.0119030752
        )

    [13] => Array
        (
            [1] => 52.886671288709
        )

    [14] => Array
        (
            [1] => 65.222695436481
        )

)
从上面的数组输出中

。是否有能力将输出更改为如下所示?

Array
(
    [1] => Array
        (
            [1] => 48.083261120685,
[13] => 52.886671288709,
[14] => 65.222695436481
        )
[2] => Array (
[3] => 38.262252939418,
[8] => 47.053161424074,
[9] => 15.58845726812,
[10] => 6.164414002969,
[12] => 42.0119030752
)

我尝试了几种方法,但是也许因为我只是一个初学者,所以我一直无法找到解决方案。请帮助朋友

1 个答案:

答案 0 :(得分:1)

您可以使用foreach

$r= [];
foreach($a as $k => $v){
  foreach($v as $k1 => $v1){
    $r[$k1][$k] = $v1;
  }
}

Working DEMO