[英]How to loop through statement results to insert into associative array in PHP
我似乎無法獲得正確的語法來循環遍歷我的結果並將它們插入到關聯數組中——目前它只給我第一個結果而不是遍歷其余的結果。 我嘗試了 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
)
這是因為您覆蓋了同一變量中的所有結果,因此當您打印結果時,您將看到寫入變量的最后數據。
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"];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.