0

I have a json file with this below format structure.

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

I would like to update the rate of the fruit by +1 when i match a search for it.

1 . Read the json file

 $json_file = file_get_contents('fruits.txt');

2 . Decoded the json file

 $fruit_list=json_decode($json_file,true);
  1. VarDumping the Decoded json file is like this

    array (size=3)
      0 => 
        array (size=3)
          'name' => string 'banana' (length=6)
          'type' => string 'fruit' (length=5)
          'rate' => int 10
      1 => 
        array (size=3)
          'name' => string 'orange' (length=6)
          'type' => string 'fruit' (length=5)
          'rate' => int 20
      2 => 
        array (size=3)
          'name' => string 'apple' (length=5)
          'type' => string 'fruit' (length=5)
          'rate' => int 30
    
  2. Wrote a search function to search the array for fruit name

function search_by_key_and_value($array, $key, $value)
{
    $results = array();

    if (is_array($array))
    {
        if (isset($array[$key]) && $array[$key] == $value)
            $results[] = $array;

        foreach ($array as $subarray)
            $results = array_merge($results, search_by_key_and_value($subarray, $key, $value));
    }

    return $results;

}

 $result = search_by_key_and_value($fruit_list,"name",apple);
  1. when the function is supplied with fruit name the whole of json file is searched and the RESULT_MATCH is printed var_dump($result) is like this below

        array (size=1)
              0 => 
                array (size=3)
                  'name' => string 'apple' (length=5)
                  'type' => string 'fruit' (length=5)
                  'rate' => int 30
    
  2. How can i find the array index number as the result of array index is 0 in the result but its position in the main file point no 3 is indexed at 2 or at-least how can i update the matched retsult rate directly ?

2
  • 1
    The only thing that matters is what the code in #4 looks like. Please provide this. Commented Sep 17, 2014 at 22:59
  • @Ohgodwhy Added #4 code for clarity , please go through it Commented Sep 17, 2014 at 23:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.