Search code examples
phparraysloopsassociative-array

How to loop through statement results to insert into associative array in PHP


I cannot seem to get the syntax correct to loop through my results and insert them into an associative array- at the moment it is only giving me the first result and not looping through the rest. I've tried numerous combinations of foreach etc but just cannot complete this successfully.

Here is my code:

$count = array(
    "timeinsert"=>"value",
    "rfid"=>"value"
  );
  
  $readlags = "SELECT id_arduino, Device_id,time_inserted, message, message_type,
                    LAG(message) OVER(PARTITION BY device_id ORDER BY time_inserted) 
                    AS 'Previous Entry'
                    FROM Arduino_Data 
                    WHERE Datediff(Curdate(), time_inserted) < $period AND Device_id = $device AND message != 2
                    GROUP BY time_inserted ASC";
  
  $result = $conn->query($readlags);
  
  if (!$result) {
      echo $conn->error;
  }
  
  while ($row = mysqli_fetch_array($result)) {
      $eventtime = $row['time_inserted'];
      $message = $row['message'];
      $message_type = $row['message_type'];
      $previous = $row['Previous Entry'];
  
      if ($previous != 'Broken' and $previous != null) {
          $catid = "SELECT RFID_id
                    FROM Cat_User
                    WHERE RFID_id = $previous ";
  
          $result1 = $conn->query($catid);
  
          if (!$result1) {
              echo $conn->error;
          }
          while ($row1 = mysqli_fetch_array($result1)) {
              $cat_id = $row1['RFID_id'];
              //echo $cat_id . '<br>';
  
              }
          }
  
       
          if ($message == "Broken" && $message_type == "BreakBeam" && $previous==$cat_id) {
              
            
            $count["timeinsert"] = $eventtime;
              $count["rfid"]=$previous;

          }
            
      }       
  

 
  print_r($count);

This is the output :

Array
(
    [timeinsert] => 2020-09-17 16:02:44
    [rfid] => 5609
)

When I do an array_push the results are the following :

Array
(
    [0] => 2020-09-17 15:51:37
    [1] => 23641
    [2] => 2020-09-17 15:52:20
    [3] => 5609
    [4] => 2020-09-17 15:53:23
    [5] => 5609
    [6] => 2020-09-17 16:02:44
    [7] => 5609
)

Solution

  • this because you overwritten all result in same variable so when you print reasult you will see last data written in variable.

    1) define $count as array and $c to count array element like this

    $count = array();
    $c=0;
    

    2) when you want to save new data but it in multidimensional array like this:

    $count[$c]["timeinsert"] = $eventtime;
    $count[$c]["rfid"]=$previous;
    $c++;
    

    3) retrieve your data like this:

    $c=count($count);
    for($i=0;$i<$c;$i++){
        echo $count[$i]["timeinsert"];
        echo $count[$i]["rfid"];
    }