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);
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
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);
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 belowarray (size=1) 0 => array (size=3) 'name' => string 'apple' (length=5) 'type' => string 'fruit' (length=5) 'rate' => int 30
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 ?