我正在根據產品名稱進行搜索。它確實有效,它確實根據搜索找到了該產品,但問題是,當我有幾個同名的產品時,它只顯示第一個產品。它如何優化?我很感謝你的幫助。使用php搜索無法正常工作
<?php
//DATA coming from the browser
$sSearch = $_GET['search'];
//TURN it into UPPERCASE
strtoupper($sSearch);
//GETTING FROM FILE:
$sajProducts = file_get_contents('products.txt');
$ajProducts = json_decode($sajProducts);
$matchfound = false;
//LOOPING THROUGH THE ARRAY OF PRODUCTS
for ($i=0; $i< count($ajProducts); $i++) {
if ($sSearch == $ajProducts[$i]->name) {
$jSearchResult = $ajProducts[$i];
$matchfound = true;
break;
}
}
//if there is a match display the product
if ($matchfound) {
echo json_encode ($jSearchResult);
exit;
}
//if not display ALL products
else {
echo json_encode($ajProducts);
exit;
}
?>
而且JSON products.text文件:
[
{
"id": "59d278cae7017",
"name": "A",
"price": "1",
"quantity": 3,
"image": "img_webshop\/productimage-59d74304917c2.jpg"
},
{
"id": "59d27e20c8028",
"name": "A",
"price": "2",
"quantity": 3,
"image": "img_webshop\/productimage-59d743233c0cf.jpg"
},
{
"id": "59d6a7ae16d15",
"name": "A",
"price": "3",
"quantity": 2,
"image": "img_webshop\/productimage-59d743392fbb5.jpg"
},
{
"id": "59d6d6ee5f752",
"name": "A",
"price": "4",
"quantity": 4,
"image": "img_webshop\/productimage-59d74352d5b94.jpg"
},
{
"id": "59d743d207bd5",
"name": "B",
"price": "5",
"quantity": 1,
"image": "img_webshop\/productimage-59d743d1e6e64.jpg"
},
{
"id": "59d74451225ac",
"name": "B",
"price": "6",
"quantity": 1,
"image": "img_webshop\/productimage-59d7445120871.jpg"
},
{
"id": "59e0d95cd4111",
"name": "B",
"price": "4",
"quantity": "5",
"image": "img_webshop\/productimage-59e0d95cd2c4b.jpg"
},
{
"id": "59e0d992d1f3b",
"name": "C",
"price": "6",
"quantity": "5",
"image": "img_webshop\/productimage-59e0d992d19be.jpg"
},
{
"id": "59e0d9c59fbf2",
"name": "D",
"price": "4",
"quantity": "5",
"image": "img_webshop\/productimage-59e0d9c59f1a5.jpg"
}
]
謝謝@codeDragon接受我的答案。樂於幫助。 –