【问题标题】:php foreach with additional condition带有附加条件的php foreach
【发布时间】:2021-09-23 13:58:39
【问题描述】:

我有一个类似的 Json 输出

{ ["id"]=> int(1) ["name"]=> string(7) "SH-Mini" ["currency"]=> int(1) ["monthly"]=> string(4) "4.99" } [79]=> object(stdClass)#301 (4) 
{ ["id"]=> int(1) ["name"]=> string(7) "SH-Mini" ["currency"]=> int(2) ["monthly"]=> string(4) "345.23" } [80]=> object(stdClass)#300 (4) 
{ ["id"]=> int(1) ["name"]=> string(7) "SH-Mini" ["currency"]=> int(6) ["monthly"]=> string(5) "4.01" } [81]=> object(stdClass)#299 (4) 
{ ["id"]=> int(19) ["name"]=> string(8) "SH-Basic" ["currency"]=> int(1) ["monthly"]=> string(4) "5.99" } [82]=> object(stdClass)#298 (4) 
{ ["id"]=> int(19) ["name"]=> string(8) "SH-Basic" ["currency"]=> int(2) ["monthly"]=> string(6) "443.44" } [83]=> object(stdClass)#297 (4) 
{ ["id"]=> int(19) ["name"]=> string(8) "SH-Basic" ["currency"]=> int(6) ["monthly"]=> string(4) "5.03" } [84]=> object(stdClass)#296 (4) 

我想得到 id 为 19,货币为 2 的值。我需要的输出是 443.44

我正在尝试将 PHP foreach 用于上述 json 解码输出。它总是给我 5.99 的第一个值

我正在使用下面的代码。

     $pid = 19;
     $cur = 2;

     foreach($products as $product){
         $getproductrrice[$product->id] = $product->monthly;
     }

     return $getproductrrice[$pid];

我需要再添加一个条件,以便我可以传递货币并获得输出为 443.44。

【问题讨论】:

  • 还有什么问题?为什么不添加那个条件?

标签: php foreach multiple-conditions


【解决方案1】:

在循环播放时,测试每个产品,看看它是否是你想要的

$pid = 19;
$cur = 2;

foreach($products as $product){
    if ( $product->id == $pid && $product->currency == $cur ) {
        $getproductrrice[$product->id] = $product->monthly;
    }
}

【讨论】:

    猜你喜欢
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多