Group subarrays by one column, make comma-separated values from other column within groups

前端 未结 2 2074
耶瑟儿~
耶瑟儿~ 2020-12-07 06:08


I have a array that looks like this:

$array = [
    [\"444\", \"0081\"],
    [\"449\", \"0081\"],
    [\"451\", \"0081\"],
    [\"455\", \"2100\         


        
2条回答
  •  隐瞒了意图╮
    2020-12-07 07:02

    Writing two loops is too much effort for this task. Use isset() with temporary keys applied to your output array as you iterate. When finished grouping the data, reindex the output with array_values().

    Code (Demo)

    $array = [
        ["444", "0081"],
        ["449", "0081"],
        ["451", "0081"],
        ["455", "2100"],
        ["469", "2100"]
    ];
    
    foreach ($array as $row) {
        if (!isset($result[$row[1]])) {
            $result[$row[1]] = $row;  // first occurrence of group, save whole row
        } else {
            $result[$row[1]][0] .= ',' . $row[0];  // not first occurrence, concat first element in group
        }
    }
    var_export(array_values($result));
    

    Output:

    array (
      0 => 
      array (
        0 => '444,449,451',
        1 => '0081',
      ),
      1 => 
      array (
        0 => '455,469',
        1 => '2100',
      ),
    )
    

提交回复
热议问题