[英]Array inside a json object and object inside a json object using php
I am trying to produce the following JSON from MySQL database using PHP. 我正在尝试使用PHP从MySQL数据库生成以下JSON。 How do I go about doing it in PHP lets say using the explode function for getting the array into the JSON object. 我该如何在PHP中做到这一点,可以说使用explode函数将数组放入JSON对象中。 I don't know about getting the JSON object inside an object. 我不知道如何在对象内部获取JSON对象。 I just need to separate PHP files to achieve the following. 我只需要分离PHP文件即可实现以下目的。
<?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM users';
$q = $pdo->prepare($sql);
$q->execute(array($sql));
$array = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)){
array_push($array, $row);
}
$json = json_encode($array);
echo $json;
Database::disconnect();?>
Array inside a JSON object: JSON对象内的数组:
[
{
"firstName":"John",
"lastName":"Doe",
"images": ['image1','image2','image3']
},
{
"firstName":"Anna",
"lastName":"Smith",
"images": ['image1','image2','image3']
},
{
"firstName":"Peter",
"lastName":"Jones",
"images": ['image1','image2','image3']
}
]
JSON object inside an object: 对象内的JSON对象:
[
{
"firstName":"John",
"lastName":"Doe",
"cover": {
"cover_id": "0858699703",
"source": "www.myimages.co.zw/images/photo",
"offset_y": "0"
}
},
{
"firstName":"Anna",
"lastName":"Smith"
"cover": {
"cover_id": "0858699703",
"source": "www.myimages.co.zw/images/photo",
"offset_y": "0"
}
},
{
"firstName":"Peter",
"lastName":"Jones"
"cover": {
"cover_id": "0858699703",
"source": "www.myimages.co.zw/images/photo",
"offset_y": "0"
}
}
]
<?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM test';
$q = $pdo->prepare($sql);
$q->execute(array($sql));
$array = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)){
$row_array['name'] = $row['name'];
$row_array['surname'] = $row['surname'];
$row_array['images'] = explode(" ", $row['images']);
array_push($array, $row_array);
}
$json = json_encode($array);
echo $json;
Database::disconnect();
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.