How to create json files from 3 php arrays?

Member

by dana , in category: PHP General , a year ago

How to create json files from 3 php arrays?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 5 months ago

@dana 

You can create JSON files from PHP arrays using the json_encode function. Here's an example of how you can create a JSON file from 3 PHP arrays:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php

// Sample PHP arrays
$firstArray = array(
    'name' => 'John Doe',
    'age' => 30,
    'city' => 'New York'
);

$secondArray = array(
    'name' => 'Jane Smith',
    'age' => 25,
    'city' => 'Los Angeles'
);

$thirdArray = array(
    'name' => 'Michael Johnson',
    'age' => 35,
    'city' => 'Chicago'
);

// Combine all arrays into one
$combinedArray = array(
    'users' => array($firstArray, $secondArray, $thirdArray)
);

// Convert the combined array to JSON format
$jsonData = json_encode($combinedArray);

// Write JSON data to a file
$filename = 'users.json';
file_put_contents($filename, $jsonData);

echo 'JSON file created successfully';
?>


This script will combine the 3 PHP arrays into a single array and convert it to JSON format using json_encode. Then, it will write the JSON data to a file named users.json. You can modify the content of the arrays and the file name to suit your needs.