[英]Search elements of an array by key value
我有以下PHP代碼,該代碼按鍵名搜索數組並返回等於搜索的結果。 出於好奇,我該怎么做,無論我搜索的結果是名稱鍵值等於“ A”的元素嗎? 不久我該如何檢索名稱為“ A”的元素?
我嘗試了以下操作,但不起作用:
$jSearchResult[] = $ajProducts[$i]->name = "A";
請幫助我,因為我只是無法弄清楚如何通過鍵值檢索數組的元素,但是我確信它一定很簡單。
<?php
//DATA coming from the BROWSER
$sSearch = $_GET['search'];
//TURN it into UPPERCASE
strtoupper( $sSearch );
//GETTING from the TEXT FILE:
$sajProducts = file_get_contents( 'products.txt' );
$ajProducts = json_decode( $sajProducts );
$match_found = false;
//Collect all matching result in an array
$jSearchResult = array();
//LOOPING THROUGH THE ARRAY OF PRODUCTS
for ( $i=0; $i< count( $ajProducts ); $i++ ) {
if ( $sSearch == $ajProducts[$i]->name ) {
$jSearchResult[] = $ajProducts[$i]->name;
$match_found = true;
}
}
//if there is a match display the product
if ( $match_found ) {
echo json_encode ( $jSearchResult );
exit;
}
//if not display ALL products
else {
echo json_encode ( $ajProducts );
exit;
}
?>
$ajProducts
看起來像這樣:
[
{
"id": "59d278cae7017",
"name": "A",
"price": "1",
"quantity": 2,
"image": "img_webshop\/productimage-59d74304917c2.jpg"
},
{
"id": "59d27e20c8028",
"name": "A",
"price": "2",
"quantity": 1,
"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": 1,
"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": 0,
"image": "img_webshop\/productimage-59d7445120871.jpg"
},
{
"id": "59e0d992d1f3b",
"name": "C",
"price": "6",
"quantity": 2,
"image": "img_webshop\/productimage-59e725ac79583.jpg"
}
]
有一個php函數可以做到這一點: http : //php.net/array_filter
$searchResult = array_filter($ajProducts, function ($product) {
return $product->name === 'A';
});
這將使您將$ajProducts
中所有具有name
屬性設置為'A'
。
查看是否有任何結果:
$matchFound = !empty($searchResult);
如果要match
name key
等於"A"
元素,則只需check
名稱鍵值等於"A"
-
foreach ($ajProducts as $ajProduct ) {
if ( "A" == $ajProduct->name ) {
$jSearchResult[] = $ajProduct->name;
$match_found = true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.