BetaCoder
BetaCoder

Reputation: 302

modifying json file values with php

I have a json file with this below exact format structure.

[  
 {  
    "name":"banana",
    "type":"fruit",
    "rate":10
 },
 {  
    "name":"orange",
    "type":"fruit",
    "rate":20
 },
 {  
    "name":"apple",
    "type":"fruit",
    "rate":30
 }
]

The goal logic would be

  1. if the fruit rate searched is 30 ,i would update it to 31

  2. if the fruit rate searched is 31 ,i would update it to 32

  3. if the fruit rate searched is 32 ,i would update it to 33

  4. if the fruit rate searched is 33 , stop updating and echo "Over Priced";

I would like to update the rate of the fruit when searched with fruit name "apple" by +1 upto +3 when i match a search for it ?.

How can i achieve the goal logic ?

I tried programming lengthy code here but it failed with finding index to modify - finding php json array index number

Upvotes: 0

Views: 85

Answers (2)

ylerjen
ylerjen

Reputation: 4259

$text = file_get_contents('fruits.txt');
$json = json_decode($text , true);
$searchedFruit = 'apple';

foreach ($json as &$fruit){
  if($fruit['name'] === $searchedFruit){
    if($fruit['rate'] >= 30 && $fruit['rate'] < 33){
      $fruit['rate']++;        
    } else if($fruit['rate'] === 33){
      echo "Over priced";
    }
  }
}

var_dump($json);

file_put_contents('fruits.txt', json_encode($json));

Upvotes: 1

Cl&#233;ment Malet
Cl&#233;ment Malet

Reputation: 5090

You went too far with your previous code

$json = '[{"name":"banana","type":"fruit","rate":31},
 {"name":"orange","type":"fruit","rate":32},
 {"name":"apple","type":"fruit","rate":33}
]';

$array = json_decode($json, true);

$maximum_rate = 32;
$searched_fruit = "apple";

foreach ($array as &$value) {
  if ($value['name'] == $searched_fruit) {
    if ($value['rate'] > $maximum_rate) {
      echo 'Over priced : ' . $value['name'] . "\n";
      break;
    } else {
      $value['rate']++;
      break;
    }
  }
}

$json = json_encode($array);

var_dump($json);

Output :

Over priced : apple
[{"name":"banana","type":"fruit","rate":31},
 {"name":"orange","type":"fruit","rate":32},
 {"name":"apple","type":"fruit","rate":33}]

Upvotes: 0

Related Questions