简体   繁体   中英

php group multidimentional array by word

I have this kind of array written on 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"]; 

I wanted to group them so the output would be

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

I tried to ksort() but not working:

$group_arr = [];
    foreach ($array as $key => $value) {
        $group_arr[$value["name"]][$key] = $value;
    }

You should try:

foreach ($array as $value) {
    $v = $value;
    unset($v['name']);
    $group_arr[$value["name"]][] = $v;
}

No use of ksort is needed. Notice the keys of $array are just integer and you don't need them in the result array

You need to make a nested loop.
In order to not add the name in the new array I extract it and use array_slice to not get it in the nested foreach.

foreach ($array as $value) {
    $name = $value["name"];
    foreach(array_slice($value,1) as $val){
        $group_arr[$name][] = $val;
    }
}
var_dump($group_arr);

Output:

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"
  }
}

https://3v4l.org/ebuFt

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