繁体   English   中英

通过键值搜索数组的元素

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM