0

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);
1
  • 1
    your for loop must start from 0 and not from 1 when you use the loop-index as key-identifier. Commented Sep 22, 2021 at 4:28

1 Answer 1

2

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};
}
...
Sign up to request clarification or add additional context in comments.

Comments

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.