我有用PHP编写的这种数组。
$array[] = ["name"=>"KIT", "v1"=>"val1", "v2"=>"val2", "v3"=>"val3"];
$array[] = ["name"=>"BAT", "v1"=>"val1", "v2"=>"val2", "v3"=>"val3"];
$array[] = ["name"=>"ISL", "v1"=>"val1", "v2"=>"val1", "v3"=>"val1"];
$array[] = ["name"=>"KIT", "v1"=>"val4", "v2"=>"val2", "v3"=>"val2"];
$array[] = ["name"=>"BAT", "v1"=>"val1", "v2"=>"val2", "v3"=>"val1"];
$array[] = ["name"=>"ENS", "v1"=>"val1", "v2"=>"val2", "v3"=>"val3"];
$array[] = ["name"=>"ENS", "v1"=>"val3", "v2"=>"val2", "v3"=>"val1"];
我想将它们分组,以便输出为
BAT val1 val2 val3
val1 val2 val1
ENS val1 val2 val3
val3 val2 val1
ISL val1 val1 val1
KIT val1 val2 val3
val4 val2 val2
我尝试ksort()
但不起作用:
$group_arr = [];
foreach ($array as $key => $value) {
$group_arr[$value["name"]][$key] = $value;
}
答案 0 :(得分:1)
您应该尝试:
sudo nano /etc/hosts
无需使用127.0.0.1
。注意foreach ($array as $value) {
$v = $value;
unset($v['name']);
$group_arr[$value["name"]][] = $v;
}
的键只是整数,结果数组中不需要它们
答案 1 :(得分:0)
您需要创建一个嵌套循环。
为了不将名称添加到新数组中,我将其提取并使用array_slice使其不嵌套在foreach中。
foreach ($array as $value) {
$name = $value["name"];
foreach(array_slice($value,1) as $val){
$group_arr[$name][] = $val;
}
}
var_dump($group_arr);
输出:
array(4) {
["KIT"]=>
array(6) {
[0]=>
string(4) "val1"
[1]=>
string(4) "val2"
[2]=>
string(4) "val3"
[3]=>
string(4) "val4"
[4]=>
string(4) "val2"
[5]=>
string(4) "val2"
}
["BAT"]=>
array(6) {
[0]=>
string(4) "val1"
[1]=>
string(4) "val2"
[2]=>
string(4) "val3"
[3]=>
string(4) "val1"
[4]=>
string(4) "val2"
[5]=>
string(4) "val1"
}
["ISL"]=>
array(3) {
[0]=>
string(4) "val1"
[1]=>
string(4) "val1"
[2]=>
string(4) "val1"
}
["ENS"]=>
array(6) {
[0]=>
string(4) "val1"
[1]=>
string(4) "val2"
[2]=>
string(4) "val3"
[3]=>
string(4) "val3"
[4]=>
string(4) "val2"
[5]=>
string(4) "val1"
}
}