Home > Back-end >  Create new JSON file from another with some changed values in PHP
Create new JSON file from another with some changed values in PHP

Time:09-22

1st JSON file with dictionary. -> dictionary.json

Array(
[label] => Name
[options] => Array
    (
        [green] => Value 1
        [blue] => Value 2
        [purple] => Value 3
    ))

2nd JSON file with products with all eng names. -> main.json

Array
(
    [0] => Array
        (
           [id] => 1
           [cat_id] => 1
           [options] => Array
               (
                   [width] = 100
                   [height] = 100
                   [color] = green
               )
         )
    etc.
)

I would like to create a new JSON file that would contain the same data as the 2nd JSON file, plus a translated values for color attribiute. The script below allows me to change the color to a value from the dictionary, but when writing to a new file the names remain the same - unchanged. Is it possible to write it with changed values?

<?php
$json = file_get_contents('main.json');
$json_dict = file_get_contents('dictionary.json');

$decoded = json_decode($json);
$decoded_dict = json_decode($json_dict);

for($i = 1; $i < count($decoded); $i  ){
    
     $temp = $decoded[$i]->options->color;
     $decoded[$i]->options->color = $decoded_dict->options->$temp;
}

$new_json = json_encode($decoded);
file_put_contents("myfile.json", $new_json);

CodePudding user response:

You should start your for loop from 0 instead 1 because array index starting from 0:

...
for($i = 0; $i < count($decoded); $i  ){
...

and I recommend to you that use foreach loop (PHP foreach doc):

...
foreach($decoded as $d){
    $temp = $d->options->color;
    $d->options->color = $decoded_dict->options->{$temp};
}
...
  • Related