PHP not showing all data in array from loop

Viewed 24

Outputting data to an array

public function GetProfitByMonth($d1, $d2){
    $sql=odbc_exec($this->connections, "select con.ID, con.ShortName as NameAK,
                            ROUND(ISNULL(SUM(tik.TotalSub)-SUM(tik.TotalAG), 0), 2) as Profit,
                            MONTH(tik.DEALDATE) as month_num
                            from Counteragent as con
                            left join Tickets as tik on tik.AgentID=con.ID
                            where con.ValueType in (2,3) and con.Active='1' and (DEALDATE between '".$d1."' and '".$d2."')
                            group by con.ID, con.ShortName, MONTH(tik.DEALDATE)
                            order by con.ShortName, MONTH(tik.DEALDATE) ;");
    $tblResult=array();
    while ($row = odbc_fetch_array($sql)) {
        $tblResult[]=$row;
    }
    odbc_free_result($sql);
   

Array
(
    [0] => Array
        (
            [Profit] => 11218.30
            [month_num] => 8
        )    
    [1] => Array
        (
            [Profit] => 1152.15
            [month_num] => 8
        )

    ....

    [4] => Array
        (
            [Profit] => 119837.81
            [month_num] => 8
        )    
)

I need to display only month_num => Profi from the array

did this way

$tblResult =  array();
        while ($row = odbc_fetch_array($sql)) {
            $tblResult[$row['mon_num']] = $row['Profit'];
        }
        odbc_free_result($sql);
        return $tblResult;

but as a result in the array shows only the last value:

Array
(
    [8] => 119837.81
)

How to make an array show all the data?

1 Answers

This is because month_num = 8 for all entries in your original array.
Your while loops first two iterations effectively evaluate to:

$tblResult[8] = 11218.30
$tblResult[8] = 1152.15

To get the result in the form you want, you need month_num to be unique.

Related