MrFoh
MrFoh

Reputation: 2701

Create new array to match number of months

I have an array like this

Array
(
    [interswitch] => Array
        (
            [0] => Array
                (
                    [month] => 8
                    [transactions] => 5
                )

            [1] => Array
                (
                    [month] => 9
                    [transactions] => 1
                )

        )

    [visa] => Array
        (
            [0] => Array
                (
                    [month] => 8
                    [transactions] => 9
                )

        )

)

The array is generated by an SQL query, which queries a table and counts the records for each month. Where [month] represents the calender month. I want to use this data with HighCharts which accepts data in this format

{name: 'Tokyo',data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1,95.6, 54.4]}

How to covert the my array to more readable array which can then be encoded by JSON and transformed to the above format I've tried this

$_monthly_gateway_usage = array(
                array(
                    "name"=>"Interswitch",
                    "data"=>$this->parse_monthly_usage_data($monthly_gateway_usage['interswitch'])
                ),
                array(
                    "name"=>"Visa",
                    "data"=>$this->parse_monthly_usage_data($monthly_gateway_usage['visa'])
                )

            );

private function parse_monthly_usage_data($usage_data = array()) {

            $months = array("1","2","3","4","5","6","7","8","9","10","11","12");
            $_d = array();
            foreach ($months as $month) {
                foreach ($usage_data as $key => $d) {
                    if($d['month'] == $month)
                    {
                        $_d[] = $d['transactions'];
                    }
                    else
                    {
                        $_d[] = 0;
                    }
                }
            }

            return $_d;
        }

Any help will be appreciated

Upvotes: 0

Views: 129

Answers (1)

Nicole Stutz
Nicole Stutz

Reputation: 516

This is a shorter form: The loop index is based on the months

$_d = array();
for($i=1;$i<=12;$i++){
    foreach($usage_data as $v){
        $_d[$i] += ($v['month']==$i) ? $v['transactions'] : 0;
    }
}

Upvotes: 1

Related Questions