第1個帶字典的JSON檔案。-> dictionary.json
Array(
[標簽] => 名稱
[options] => Array (
(
[green] => Value 1 (
[藍色] => 數值2
[紫色] => 值3。
))
第2個JSON檔案,包含所有eng名稱的產品。-> main.json
Array
(
[0] => Array[/span
(
[id] => 1 [cat_id] =>
[cat_id] =>1
[options] => Array[/span
(
[寬度] = 100 Array (
[高度] = 100
我想創建一個新的JSON檔案,其中包含與第2個JSON檔案相同的資料,外加一個翻譯后的顏色屬性值。 下面的腳本允許我把顏色改成字典中的一個值,但是當寫到一個新的檔案時,名字還是一樣的,沒有變化。有沒有可能用改變的值來寫呢?
<?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) 。
uj5u.com熱心網友回復:
你應該從0而不是1開始你的for回圈,因為陣列索引從0開始:
...
for($i = 0。$i < count($decoded); $i ){
...
我向你推薦使用foreach回圈(PHP foreach doc):
...
foreach($decoded as $d){
$temp = $d->options-> color;
$d->options->color = $decoded_dict->options->{$temp};
}
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/333701.html
標籤:
上一篇:C#基礎的誤用?
