【发布时间】:2022-01-18 19:46:30
【问题描述】:
我在 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"
}
john.json
{
"name": "john",
"car": "mercedes",
"color": "gray"
}
上面的代码我没有成功:字段 car 和 color 在每个 json 文件中保持为空...
【问题讨论】:
-
不可重现 - 演示:sandbox.onlinephpfunctions.com/code/… ...虽然逻辑仍然是错误的,因为由于内部循环,所有这些都是“灰色”和“梅赛德斯”。但这些字段肯定不是空的。