[英]Why is my conditional statement not executing multiple times in a foreach loop? PHP
我試圖打印出與客戶列表匹配的訂單信息,具體取決於訂單上的客戶 ID 是否與客戶的客戶 ID 匹配。 客戶和訂單都存儲在數組中,到目前為止,我在執行訂單表和打印信息方面沒有問題。 我遇到的問題是只有一個訂單正在為客戶打印,而有些客戶有多個訂單應該打印。 我使用 foreach 循環遍歷匹配訂單 ID 的訂單到請求的客戶 ID,它來自查詢字符串。 當我知道至少有 1 個正在打印時,我不知道為什么我的 if 語句沒有為多個訂單打印。
這是我的客戶表的代碼,當查詢字符串返回客戶 ID 時執行。 底部的 foreach 循環是我希望打印所有匹配訂單的地方,但當我希望在某些情況下有多個訂單時,它只給我一個訂單。 如果需要其他信息,我可以提供。 謝謝
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
if (isset($_GET['customer'])) {
$requestedCustomer = $customers[$_GET['customer']];
$orders = readOrders('orders.txt');
// <!-- orders panel -->
echo '<br><br><br>';
echo '<div class="panel panel-danger spaceabove">';
echo '<div class="panel-heading">';
echo '<h4>Orders for ' . $requestedCustomer['name'] . '</h4>';
echo '</div>';
echo '<table class="table">';
echo '<tr>';
echo '<th>ISBN</th>';
echo '<th>Title</th>';
echo '<th>Category</th>';
echo '</tr>';
foreach ($orders as $order) {
if ($requestedCustomer['id'] == $order['id']) {
echo '<tr>';
echo '<td>' . $order['isbn'] . '</td>';
echo '<td>' . $order['title'] . '</td>';
echo '<td>' . $order['category'] . '</td>';
echo '</tr>';
}
}
}
echo '</table>';
// foreach ($orders as $order) {
// if ($order['id'] == $requestedCustomer['id']) {
// }
}
?>
您是否檢查過為什么會發生這種情況? 一個單一的ID不能使用多個時間在同一陣列中,因此,如果解析多個行具有相同的ID,並將其寫入到使用相同的ID,要覆蓋現有的訂單陣列。 只能訪問具有該 ID 的最后一個訂單。 通過比較解析的訂單數組和包含訂單的文件,這應該很容易看到。
這就是為什么您通常使用唯一的訂單 ID,並將用戶 ID 存儲在該訂單中
我認為您的問題出在readOrders
。 你似乎每次都用$orders[$order['id']] = $order;
來破壞你的數組$orders[$order['id']] = $order;
相反,您想要$orders[$order['id']][] = $order;
function readOrders($filename)
{
$arr = file($filename) or die('ERROR: Cannot find file');
// Create our primary order array
$orders = [];
$delimiter = ',';
// reading in customers from file and storing in array of customers
foreach ($arr as $line) {
$splitcontents = explode($delimiter, $line);
$order = array();
$order['id'] = $splitcontents[1];
$order['isbn'] = $splitcontents[2];
$order['title'] = utf8_encode($splitcontents[3]);
$order['category'] = utf8_encode($splitcontents[4]);
// Append the order to the array,
$orders[$order['id']][] = $order;
}
return $orders;
}
然后,在您的打印循環中,您不會遍歷$orders
,而是使用由客戶 ID 索引的主訂單數組並獲取這些特定訂單。
// Get the orders for this specific customer, if they exist
$customerOrders = $orders[$requestedCustomer['id']] ?? [];
foreach ($customerOrders as $order) {
echo '<tr>';
echo '<td>' . $order['isbn'] . '</td>';
echo '<td>' . $order['title'] . '</td>';
echo '<td>' . $order['category'] . '</td>';
echo '</tr>';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.