微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有附加条件的 php foreach

如何解决带有附加条件的 php foreach

我有一个类似的 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 的输出

解决方法

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

$pid = 19;
$cur = 2;

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。