phparrayscodeignitergroupingcounting

Group and count data from multiple database queries to make an associative 2d array


Can someone please explain how to obtain this result from the following array? Here is the result I am looking for:

Array
(
    [Nov 18, 2011] => Array
        (
            [C] => 2
            [I] => 1
        )

    [Nov 22, 2011] => Array
        (
            [C] => 2
        )

)

And here is the array with the raw data:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [Nov 18, 2011] => C
                )

            [1] => Array
                (
                    [Nov 18, 2011] => C
                )

            [2] => Array
                (
                    [Nov 18, 2011] => I
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [Nov 22, 2011] => C
                )

            [1] => Array
                (
                    [Nov 22, 2011] => C
                )

        )

)

The first array shown represents the the count of items for each element of the inner array, which is what I am trying to summarize from the next array.

Here is the script which generates the above array:

$qrybilled = $this->db->query("SELECT tbltc.BILLED FROM tbltc WHERE tbltc.PN = $pn AND tbltc.Y = $taxyear AND tbltc.SCENARIO = $scenario GROUP BY BILLED");
$x = 0; $arr_billed = array();

foreach ($qrybilled->result() as $row) {
$qry3 = $this->db->query("SELECT tbltc.* FROM tbltc WHERE tbltc.PN = $pn AND tbltc.Y = $taxyear AND tbltc.SCENARIO = $scenario AND tbltc.BILLED = '".$row->BILLED."' GROUP BY TC ORDER BY CAT ASC, TC ASC");
    
    $tmp3 = array();
    foreach ($qry3->result() as $row) {     
        $tmp3[] = array( date("M d, Y",strtotime($row->BILLED)) => $row->CAT);
    }
    $arr_billed3[] = $tmp3; 

}
$data['billed3'] = $arr_billed3;

Solution

  • $arr[0][] = array('Nov 18, 2011'=>'C');
    $arr[0][] = array('Nov 18, 2011'=>'C');
    $arr[0][] = array('Nov 18, 2011'=>'I');
    
    $arr[1][] = array('Nov 22, 2011'=>'C');
    $arr[1][] = array('Nov 22, 2011'=>'C');
    
    $result = array();
    foreach($arr as $key=>$value){
        foreach($value as $k=>$v){
            foreach($v as $_k=>$_v){
                if(isset($result[$_k][$_v])){
                    $result[$_k][$_v]++;
                }
                else {
                    $result[$_k][$_v] =1;
                }
            }
        }
    }
    

    Array result:

    print_r($result);
    
    Array
    (
        [Nov 18, 2011] => Array
            (
                [C] => 2
                [I] => 1
            )
    
        [Nov 22, 2011] => Array
            (
                [C] => 2
            )
    
    )