How to group subarrays by a column value?

前端 未结 18 1780
一生所求
一生所求 2020-11-22 10:43

I have the following array

Array
(
    [0] => Array
        (
            [id] => 96
            [shipping_no] => 212755-1
            [part_no] =&         


        
18条回答
  •  渐次进展
    2020-11-22 11:06

    Recursive function grouping 2-dimensional array by keys from first to last

    Input:

    $arr = array(
        '0' => array(
            'key0' => 'value0',
            'key1' => 'value1',
            'key2' => 'value02',
        ),
        '2' => array(
            'key0' => 'value0',
            'key1' => 'value1',
            'key2' => 'value12',
        ),
        '3' => array(
            'key0' => 'value0',
            'key1' => 'value3',
            'key2' => 'value22',
        ),
    );
    $keys = array('key0', 'key1', 'key2');
    

    Output:

    $arr = array(
        'value0' => array(
            'value1 => array(
                'value02' => null,
                'value12' => null,
            ),
            'value3' => 'value22',
        ),
    );
    

    Code:

    function array_group_by_keys(&$arr, $keys) {
    
        if (count($arr) < 2){
            $arr = array_shift($arr[0]);
            return;
        }
    
        foreach ($arr as $k => $item) {
            $fvalue = array_shift($item);
            $arr[$fvalue][] = $item;
            unset($arr[$k]);
        }
    
        array_shift($keys);
        foreach ($arr as &$sub_arr) {
            array_group_by_keys($sub_arr, $keys);
        }
    }
    

提交回复
热议问题