問題描述
我有一個看起來像這樣的數(shù)組:
I have a array that looks like this:
$array = [
["444", "0081"],
["449", "0081"],
["451", "0081"],
["455", "2100"],
["469", "2100"]
];
我需要分組為一個新數(shù)組,如下所示:
I need to group as a new array that looks like:
array (
0 =>
array (
0 => '444,449,451',
1 => '0081',
),
1 =>
array (
0 => '455,469',
1 => '2100',
),
)
我嘗試了很多腳本,但都沒有成功.
I'd tried many scripts, but with no success.
function _group_by($array, $key) {
$return = array();
foreach($array as $val) {
$return[$val[$key]][] = $val;
}
return $return;
}
$newArray = _group_by($array, 1); // (NO SUCCESS)
推薦答案
應(yīng)該有更優(yōu)雅的解決方案,但我能想到的最簡單的就是這個.
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];
}
我還沒有測試過這個,但類似的東西應(yīng)該可以解決問題.這只是通過給定的數(shù)組并以結(jié)構(gòu)化的方式收集所有條目(因此 $groups
變量將包含每個共享密鑰的組的數(shù)組條目,并且該密鑰將對應(yīng)于每個給定數(shù)組中的項目).從那里開始,它只是重組它以獲得您要求的格式.
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
這篇關(guān)于按一列對子數(shù)組進行分組,從組內(nèi)的其他列生成逗號分隔的值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!