且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过一列对子数组进行分组,并在组内将逗号分隔值与另一列进行比较

更新时间:2023-08-26 11:43:10

应该有更优雅的解决方案,但我能想到的最简单的解决方案就是这个.

There should be more elegant solutions, but simplest one I can think of would be this.

// The data you have pasted in the question
$data = []; 
$groups = [];

// Go through the entire array $data
foreach($data as $item){
    // If the key doesn't exist in the new array yet, add it       
    if(!array_key_exists($item[1], $groups)){
        $groups[$item[1]] = [];
    }

    // Add the value to the array
    $groups[$item[1]][] = $item[0];
}

// Create an array for the data with the structure you requested
$structured = [];
foreach($groups as $group => $values){
    // With the array built in the last loop, implode it with a comma
    // Also add the 'key' from the last array to it ($group)
    $structured[] = [implode(',', $values), $group];
}

我还没有测试过,但是类似的方法应该可以解决.这简单地遍历给定数组并以结构化方式收集所有条目(因此$groups变量将为共享键的每个组包含一个数组条目,并且该键将对应于给定数组中每个条目的第二个条目) .从那里开始,就只是对其进行重组以获取所需的格式.

I haven't tested this but something similar should do the trick. This simply goes through the given array and collects all entries in a structurized manner (so $groups variable will contain an array entry for each group sharing a key, and the key will correspond to the 2nd item in each item within the given array). From there it's just about restructuring it to get the format you have requested.

http://php.net/manual/en/control-structures .foreach.php