【问题标题】:How to loop through statement results to insert into associative array in PHP如何遍历语句结果以插入 PHP 中的关联数组
【发布时间】:2021-01-12 12:38:03
【问题描述】:

我似乎无法获得正确的语法来循环遍历我的结果并将它们插入到关联数组中——目前它只给我第一个结果,而不是遍历其余的结果。我尝试了许多 foreach 等的组合,但无法成功完成。

这是我的代码:

$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);

这是输出:

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

当我执行 array_push 时,结果如下:

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
)

【问题讨论】:

    标签: php arrays loops associative-array


    【解决方案1】:

    这是因为您在相同的变量中覆盖了所有结果,所以当您打印结果时,您将看到最后写入变量的数据。

    1) 定义 $count 为数组,定义 $c 来计算数组元素,像这样

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

    2)当你想保存新数据但它是这样的多维数组时:

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

    3) 像这样检索您的数据:

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

    【讨论】:

    • 非常感谢,我想知道如何让输出将两个结果分组到一个数组中?例如 [0] => 数组 ( timeinsert] => 2020-09-17 16:02:44 [rfid] => 5609) 现在结果是这样的 [0] => 数组 ( [timeinsert] => 2020- 09-17 15:51:37) [1] => 数组 ([rfid] => 23641)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    相关资源
    最近更新 更多