我在 php 中有 3 個陣列,我想為每個值創建一個 json 檔案:
$aa = array('jack', 'joe', 'john');
$bb = array('audi', 'bmw', 'mercedes');
$cc = array('red', 'blue', 'gray');
foreach($aa as $a) {
$data['name'] = $a;
foreach($bb as $b) {
$data['car'] = $b;
}
foreach($cc as $c) {
$data['color'] = $c;
}
$data_file = 'data/'.$a.'.json'; // jack.json and joe.json and john.json
$json_data = json_encode($data, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
file_put_contents($data_file,$json_data);
}
我的 json 檔案應該是這樣的:
jack.json
{
"name": "jack",
"car": "audi",
"color": "red"
}
喬.json
{
"name": "joe",
"car": "bmw",
"color": "blue"
}
約翰.json
{
"name": "john",
"car": "mercedes",
"color": "gray"
}
我在上面的代碼中沒有成功:每個 json 檔案中的car和color欄位都為空...
uj5u.com熱心網友回復:
你的回圈邏輯沒有多大意義。
您正在遍歷 array $aa,在該回圈中,您將遍歷每個$bb和$cc。
相反,由于所有 3 個陣列具有相同的長度和索引,我們可以使用 1 個單回圈,獲取鍵,并使用該鍵呼叫所有 3 個陣列:
<?php
$aa = array('jack', 'joe', 'john');
$bb = array('audi', 'bmw', 'mercedes');
$cc = array('red', 'blue', 'gray');
foreach($aa as $k => $a) {
$data = [];
$data['name'] = $aa[$k];
$data['car'] = $bb[$k];
$data['color'] = $cc[$k];
$data_file = 'data/' . $aa[$k] . '.json'; // (jack.json or joe.json or john.json)
$json_data = json_encode($data, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
echo 'Writing to: ' . $data_file . PHP_EOL;
var_dump($json_data);
}
將輸出:
Writing to: data/jack.json
string(61) "{
"name": "jack",
"car": "audi",
"color": "red"
}"
Writing to: data/joe.json
string(60) "{
"name": "joe",
"car": "bmw",
"color": "blue"
}"
Writing to: data/john.json
string(66) "{
"name": "john",
"car": "mercedes",
"color": "gray"
}"
出于演示目的var_dump而使用offfile_put_contents
在線試試吧!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/382262.html
