Home > Blockchain >  how to create json files from 3 php arrays
how to create json files from 3 php arrays

Time:12-16

I have 3 arrays in php and i want to create for each value a json file:

$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);
    
}

My json files should look like this:

jack.json

{
  "name": "jack",
  "car": "audi",
  "color": "red"
}

joe.json

{
  "name": "joe",
  "car": "bmw",
  "color": "blue"
}

john.json

{
  "name": "john",
  "car": "mercedes",
  "color": "gray"
}

I do not succeed in it with the code above: fields car and color stay empty in each json file...

CodePudding user response:

Your looping logic doesn't make that much sense.

You're looping over array $aa, and in that loop, you'll loop over each $bb and $cc.


Instead, since all 3 arrays have the same length and so index, we can use 1 single loop, get the key, and call all 3 array's with that key:

<?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);
}

Will output:

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"
}"

Using var_dump instead off file_put_contents for demo purposes


Try it online!

  • Related