简体   繁体   中英

How to group an array based on values

I have a multidimensional array and I want to group it based on the second key.

for example I have an array output as follows :

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
        )

)

from the array output as above. is it possible if with a little ability to change the output to be as follows:

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
)

I have tried several ways, but maybe because I am only a beginner, I have not been able to find a solution. please help friend

You can use foreach

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

Working DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM