Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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 ?

share|improve this question
1  
The only thing that matters is what the code in #4 looks like. Please provide this. – Ohgodwhy Sep 17 '14 at 22:59
    
@Ohgodwhy Added #4 code for clarity , please go through it – BetaCoder Sep 17 '14 at 23:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.