简体   繁体   中英

Fill missing array values with zero if an array is empty in php mysql

i want to produce an array in this format [x,x,x] where each x is grouped by the addition of each retail id, however, for an empty array list, i want to have [x,x,0] assuming the third array is empty, instead of [x,x]

Below is my code

    <?php
$q = "SELECT DISTINCT outletid FROM " . TBL_SALES_LOGS;
$result = $database->query($q);
$outlets = [];
?>
data: [<?php
while ($row = $result->fetch_assoc()) {
    // $outletname = $row['title'];
    $outlet_id = $row['outletid'];
    $outlets[] = $row['outletid'];
    $amount = $row['amount'];
    ?>
    <?php echo $outlet_id; ?>,
<?php } ?> ]

data: [<?php
$outlet = implode("','", $outlets);
$qsum3 = "SELECT  outletid, SUM(amount) AS totalsum FROM " . TBL_SALES_LOGS . " WHERE outletid IN ('{$outlet}') and fueltype='PMS' group by `outletid`";
$qresult3 = $database->query($qsum3);
while ($rowq3 = $qresult3->fetch_assoc()) {
    $tot3 = $rowq3['totalsum'];
    ?>'<?php echo $tot3; ?>',<?php } ?>]

instead of having [3,4,2,3] and missing value not showing, i want to have [3,4,2,0,3] for the missing values, assuming 0 is the missing values

thanks

I have made a few changes. Mostly created a key value array depending on the id as the key, and setting all those values to sum => 0. Then, when you loop through all of the id and their sum's it changes the sum of the id's it finds.

It is untested, but should solve it. You may need to change the end. It was messy with all the opening and closing php tags.

<?php
$q = "SELECT DISTINCT outletid FROM " . TBL_SALES_LOGS;
$result = $database->query($q);
$outlets = [];
$outletsIdSum = [];
?>
data: [<?php
while ($row = $result->fetch_assoc()) {
    // $outletname = $row['title'];
    $outlet_id = $row['outletid'];
    $outlets[] = $outlet_id;
    $outletsIdSum[(int)$outlet_id] = 0;
    $amount = $row['amount'];
    ?>
    <?php echo $outlet_id; ?>,
<?php } ?> ]

data: [<?php
$outlet = implode("','", $outlets);
$qsum3 = "SELECT  outletid, SUM(amount) AS totalsum FROM " . TBL_SALES_LOGS . " WHERE outletid IN ('{$outlet}') and fueltype='PMS' group by `outletid`";
$qresult3 = $database->query($qsum3);
while ($rowq3 = $qresult3->fetch_assoc()) {
    $outletsIdSum[(int)$rowq3['outletid']] = $rowq3['totalsum'];
}
echo "'" . implode( "','", $outletsIdSum );
    ?>]

add if condition on array

<?php
     foreach(some_array as a)
       {
      if(a=="" or a==NULL)
        a=0;
    }
?>

this will check array element which is empty and then ,if it is empty it will assign array element to '0'

use this algorithm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM