数组中的PHP组值

时间:2018-09-28 11:35:52

标签: php arrays grouping

我有这个数组:

Array ( 
    [061716v] => 1 
    [061610A] => 1 
    [062433AP] => 1 
    [063868M] => 2 
    [059173V] => 3 
    [061579A] => 3 
    [062404AP] => 3 
    [059179V] => 4 
    [061582A] => 4 
    [061697V] => 4 
    [062407AP] => 4 
)

我怎么能得到这个:

Array ( 
    [1] => 061716v,061610A,062433AP 
    [2] => 063868M 
    [3] => 059173V,061579A,062404AP 
    [4] => 059179V,061582A,061697V,062407AP 
)

2 个答案:

答案 0 :(得分:5)

在PHP中,单个foreach()将完成此任务:-

$final_array = [];

foreach($initial_array as $key=>$val){

    $final_array[$val] = isset($final_array[$val]) ? $final_array[$val].','.$key : $key;

}

print_r($final_array);

输出:-{https://3v4l.org/lSKE2

答案 1 :(得分:1)

// You also can use implode to skip isset checks
$group = [];

foreach ($initialArray as $key => $value) {
    $group[$value][] = $key;
}

$result = array_map(function($v) { return implode(",",$v); }, $group);

print_r($result);