我正在尝试使用PHP从MySQL数据库生成以下JSON。我如何在PHP中进行操作让我们说使用explode函数将数组放入JSON对象中。我不知道如何在对象中获取JSON对象。我只需要分离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();?>
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对象:
[
{
"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"
}
}
]
答案 0 :(得分:1)
<?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();
?>