简体   繁体   中英

How to assign value to an array in while loop in php from mysqli result to make a counter to filter another while loop?

How to assign value to an array in while loop in php from mysqli result to make a counter to filter another while loop??

I want to assign something like this for my counter variable:

$counter = array("6:00 Am" => 0, "8:00 Am" => 0, "10:00 Am" => 0);

For this code:

//This is from transaction table
$stm2 = "SELECT tr_sched FROM transaction WHERE tr_date = CURRENT_DATE()";
$res2 = $conn->query($res2);
while($rows5 = $res2->fetch_assoc())
{
  //Not working
  $counter[] = array($rows5['tr_sched'] => 0)
}

So I can filter this another while loop if the schedule time is greater than to my limit variable, like this:

//This is from my schedule table
$stm = "SELECT sc_time FROM schedule GROUP BY sc_time";
$res = $conn->query($stm);
$counter = array();
while($row4 = $res4->fetch_assoc())
{
  //Note working
  if($counter[$row4['sc_time']] >= $limit/*=10*/)
  {
  echo "<option disabled="">" . $row4['sc_time'] . "</option>";
  }
  else
  {
  echo "<option>" . $row4['sc_time'] . "</option>";
  }
}

The goal of all the codes above is to display all schedule time from schedule table as an option for select element and if the schedule time is already have a 10 records or greater than(limit variable) on my transaction table for today it will display as option but disable so it can't be selected by user. I hope you get what I mean, I will try to keep active to answer if you have something to clarify about my question.

You don't need the while loop at all.

You can use array functions to populate the array with static values.

$stm2 = "SELECT tr_sched FROM transaction WHERE tr_date = CURRENT_DATE()";
$res2 = $conn->query($stm2);
// get values from a single column
$keys = array_column($res2->fetch_all(MYSQLI_ASSOC), 'tr_sched');
// create an array with all values as 0 and keys from $keys
$counter = array_fill_keys($keys, 0);

Of course, don't reset the array later on with $counter = array();

If you want to loop anyway, then you can use a simple foreach loop.

$stm2 = "SELECT tr_sched FROM transaction WHERE tr_date = CURRENT_DATE()";
$res2 = $conn->query($stm2);
foreach($res2 as $rows5) {
    $counter[$rows5['tr_sched']] = 0;
}

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