在PHP中将每个具有唯一值的重复名称的二维数组转换为具有多个值的唯一名称的二维数组的最有效方法?

sw1*_*456 0 php

像这样转换数组的最有效方法是什么:

[ [ 'Quiz 1' , 89 ] , ['Quiz 2' , 78] , ['Quiz 1' , 56] , ['Quiz 1' , 25] , ['Quiz 2' , 87] , ['Quiz 3' , 91] ]
Run Code Online (Sandbox Code Playgroud)

对此:

[ [ 'Quiz 1' , 89, 56, 25] , ['Quiz 2' , 78, 87] , ['Quiz 3' , 91] ]
Run Code Online (Sandbox Code Playgroud)

在 PHP 中?

Mar*_* AO 5

Iterating in a foreach loop is the most efficient way to do it, if you mean the best-performing. It may not be the most elegant way. You could also use array_map or other such; for each their preference. In any case, by using the Quiz number as a grouping key. Here's for the simples:

$vars = [ [ 'Quiz 1' , 89 ] , ['Quiz 2' , 78] , ['Quiz 1' , 56] , ['Quiz 1' , 25] , ['Quiz 2' , 87] , ['Quiz 3' , 91] ];

$grouped = [];
foreach($vars as $var) {
    empty($grouped[$var[0]]) && $grouped[$var[0]] = [$var[0]]; // If Quiz # must go in.
    $grouped[$var[0]][] = $var[1];
}
Run Code Online (Sandbox Code Playgroud)

Output:

Array [
    [Quiz 1] => [
        [0] => Quiz 1
        [1] => 89
        [2] => 56
        [3] => 25
    ]
    [Quiz 2] => [
        [0] => Quiz 2
        [1] => 78
        [2] => 87
    ]
    [Quiz 3] => [
        [0] => Quiz 3
        [1] => 91
    ]
]
Run Code Online (Sandbox Code Playgroud)

You will notice that the values are grouped with Quiz # as a key. (Necessary.) Making the first entry in the array redundant. If you don't need the in-array Quiz number, comment out the first line of the loop. If you need it and don't like the Quiz numbers used as keys, finish up with $grouped = array_values($grouped); to revert to a plain numerical index.