gpt4 book ai didi

php - 使用 php 的 json 对象内的数组和 json 对象内的对象

转载 作者:行者123 更新时间:2023-11-29 12:32:02 25 4
gpt4 key购买 nike

我正在尝试使用 PHP 从 MySQL 数据库生成以下 JSON。我该如何在 PHP 中执行此操作,比如说使用爆炸函数将数组放入 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"
}
}
]

最佳答案

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

关于php - 使用 php 的 json 对象内的数组和 json 对象内的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27335659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com