像这样转换数组的最有效方法是什么:
[ [ '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 中?
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.
| 归档时间: |
|
| 查看次数: |
31 次 |
| 最近记录: |