Renegade Rob
Renegade Rob

Reputation: 403

PHP Changing values in a Variable based on JSON feed value

I get a discount value from a JSON feed called $response

The JSON feed is {"discount":"15%"}

I want to read that value and increment another variable based on the original.

The script I have is

$nd = "";

$d0 = "10%";
$d1 = "15%";
$d2 = "20%";
$d3 = "30%";
$d4 = "40%";


$response1 = json_decode($response,true);

foreach($response1->discount as $ed){

if($ed == $d0){ $nd = $d1; }
elseif($ed == $d1){ $nd = $d2; }
elseif($ed == $d2){ $nd = $d3; }
elseif($ed == $d3){ $nd = $d4; }
else {$nd = "10%";}
}

When I output the values I get nothing in both $ed (existing discount) and $nd (new Discount)

Upvotes: 1

Views: 47

Answers (2)

Happy Coding
Happy Coding

Reputation: 2525

Try this :

$result['discount'] = '15%';
$response = json_encode($result);

$nd = "";

$d0 = "10%";
$d1 = "15%";
$d2 = "20%";
$d3 = "30%";
$d4 = "40%";


$response1 = json_decode($response,true);

foreach($response1 as $ed){

if($ed == $d0){ $nd = $d1; }
elseif($ed == $d1){ $nd = $d2; }
elseif($ed == $d2){ $nd = $d3; }
elseif($ed == $d3){ $nd = $d4; }
else {$nd = "10%";}
}

echo $ed.''.$nd;

Upvotes: 1

Maha Dev
Maha Dev

Reputation: 3965

$response1 is object not $response1->discount. So your loop will be like this:

foreach($response1 as $ed){

if($ed->discount == $d0){ $nd = $d1; }
elseif($ed->discount == $d1){ $nd = $d2; }
elseif($ed->discount == $d2){ $nd = $d3; }
elseif($ed->discount == $d3){ $nd = $d4; }
else {$nd = "10%";}
}

Upvotes: 1

Related Questions