0

This is my sample.json file

  "general": {
    "option_name" : "option_name",
    "filter_name" : "filter name"
}

and I want to update the value using key

$string = "general.filter_name";

$updateContent = "new filtername";

$langArray = explode('.',$string);

print_r($langArray);

/*Array
(
[0] => general
[1] => filter_name
) */


$file='assets/sample.json';

$jsonString = file_get_contents($file);
$data = json_decode($jsonString, true);

**$data['general']['filter_name'] = $updateContent; **


$newJsonString = json_encode($data);
file_put_contents($file, $newJsonString);

Here I want to assign Array

 [0] => general
 [1] => filter_name

should be

$data['general']['filter_name']

How to define array like this? Thanks

MGM
  • 223
  • 1
  • 13

1 Answers1

1

You can do it using references:

$json = file_get_contents('assets/sample.json');
$json = json_decode($json, true);

$path = "general.filter_name";
$path = explode('.', $path);

$ref = &$json;

foreach ($path as $key) {
    $ref = &$ref[$key];
}

$ref = "new filtername";
unset($ref);

How it works:

  1. Create a reference for your array: $ref = &$json;
  2. Iterate through $path items to get value of $json['general']['filter_name']:
    1. On the first iteration $ref will be reference to $json['general']
    2. On the second iteration $ref will be reference to $json['general']['filter_name'] - that's exactly what we want
  3. When assign $ref = "new filtername"; you're assigning $json['general']['filter_name'] = "new filtername";
  4. Don't forget to remove reference unset($ref);, without doing it there is possibility to change $ref and thus to change $json['general']['filter_name']
krlv
  • 2,310
  • 1
  • 12
  • 15