Vĩ Lương Vĩ Lương - 5 months ago 9
PHP Question

Group by multi array with $key is object in php

I have an Array, I want to group by object with key is a object.

0: {cou_id: "140", number: "1", opera: [["1", "2"]]}
1: {cou_id: "141", number: "1", opera: [["1", "2"]]}
2: {cou_id: "140", number: "4", opera: [["3", "4"]]}
4: {cou_id: "141", number: "2", opera: [["2", "3"]]}


I want to group this array by 'cou_id' and push number into array_number, push opera into array_opera.
The results would be something like:

140: { array_number : [1,4], array_opera: [[1,2],[3,4]] }
141: { array_number : [1,2], array_opera: [[1,2],[2,3]] }


Please help me! Thanks!! I'm sorry my english isn't good.

Answer

I think you are looking for this:

$arr = array(
        array('cou_id' => "140", 'number' => "1", 'opera' => array("1", "2")),
        array('cou_id' => "141", 'number' => "1", 'opera' => array("1", "2")),
        array('cou_id' => "140", 'number' => "4", 'opera' => array("3", "4")),
        array('cou_id' => "141", 'number' => "2", 'opera' => array("2", "3"))   
    );

$out = array();
foreach($arr as $val){
    $out[$val['cou_id']]['array_number'][] = $val['number'];
    $out[$val['cou_id']]['array_opera'][] = $val['opera'];
}

echo '<pre>';
print_r($out);

Output:

Array
(
    [140] => Array
        (
            [array_number] => Array
                (
                    [0] => 1
                    [1] => 4
                )

            [array_opera] => Array
                (
                    [0] => Array
                        (
                            [0] => 1
                            [1] => 2
                        )

                    [1] => Array
                        (
                            [0] => 3
                            [1] => 4
                        )

                )

        )

    [141] => Array
        (
            [array_number] => Array
                (
                    [0] => 1
                    [1] => 2
                )

            [array_opera] => Array
                (
                    [0] => Array
                        (
                            [0] => 1
                            [1] => 2
                        )

                    [1] => Array
                        (
                            [0] => 2
                            [1] => 3
                        )

                )

        )

)
Comments