Search code examples
phpforeachmultiple-conditions

php foreach with additional condition


I Have a Json output like

{ ["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) 

I want to get the value with id as 19 and currency as 2. The output I require is 443.44

I was trying using PHP foreach for the above json decoded output. It always gives me the first value of 5.99

I am using the below code.

     $pid = 19;
     $cur = 2;

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

     return $getproductrrice[$pid];

I need to add one more condition so that I can pass currency and get the output as 443.44.


Solution

  • AS you are looping, test each product to see if it is one you want

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