【问题标题】:how to create json files from 3 php arrays如何从 3 个 php 数组创建 json 文件
【发布时间】: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"
}

上面的代码我没有成功:字段 carcolor 在每个 json 文件中保持为空...

【问题讨论】:

  • 不可重现 - 演示:sandbox.onlinephpfunctions.com/code/… ...虽然逻辑仍然是错误的,因为由于内部循环,所有这些都是“灰色”和“梅赛德斯”。但这些字段肯定不是空的。

标签: php arrays json


【解决方案1】:

您的循环逻辑没有多大意义。

您正在循环遍历数组 $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 而不是关闭file_put_contents 用于演示目的


Try it online!

【讨论】:

  • 同意这更合乎逻辑,尽管 OP 的原始代码似乎没有产生他们报告的错误(但它确实包含不同的逻辑缺陷,此代码已更正)。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多