我将我的结果编码为json,我想合并它们。我希望实现这个目标
[
{
"post_id": 1,
"content": "test image feature",
"date": "0000-00-00",
"category_id": 1,
"lp_title": "",
"lp_image": "",
"lp_canonicalUrl": "",
"lp_url": "",
"lp_desc": "",
"lp_iframe": "",
"lp_iframe_id": ""
"img_src" [{img_src:1.jpg},{img_src:2.jpg}]
}
]
每个陈述的结果
[
{
"img_src": "1.jpg"
},
{
"img_src": "2.jpg"
}
]
下一个
[
{
"post_id": 1,
"content": "test image feature",
"date": "0000-00-00",
"category_id": 1,
"lp_title": "",
"lp_image": "",
"lp_canonicalUrl": "",
"lp_url": "",
"lp_desc": "",
"lp_iframe": "",
"lp_iframe_id": ""
}
]
答案 0 :(得分:3)
您可以将JSON解码为数组,将其附加到另一个数组,然后重新编码:
$s1 = '[
{
"img_src": "1.jpg"
},
{
"img_src": "2.jpg"
}
]';
$s2 = '[
{
"post_id": 1,
"content": "test image feature",
"date": "0000-00-00",
"category_id": 1,
"lp_title": "",
"lp_image": "",
"lp_canonicalUrl": "",
"lp_url": "",
"lp_desc": "",
"lp_iframe": "",
"lp_iframe_id": ""
}
]';
//decode each
$arr1 = json_decode($s1, true);
$arr2 = json_decode($s2, true);
$arr2[0]['img_src'] = $arr1;
//re-encode as a JSON string and show output
$sf = json_encode($arr2);
echo $sf;
这应该给出你描述的结果,“img_src”...作为较大集合的子数组。
答案 1 :(得分:0)
看看你的PHP代码,你也可以一次性这样做。
$stmt = $db->prepare("
SELECT post_id,content,date,category_id,lp_title,lp_image,lp_canonicalUrl,lp_url,lp_desc,lp_iframe,lp_iframe_id
FROM post_items inner JOIN user ON post_items.user_id = user.user_id
WHERE post_items.user_id = ? order by post_items.post_id desc LIMIT ?,?");
$stmt->bind_param('iii', $userid, $itemStart, $itemEnd);
$stmt2 = $db->prepare("SELECT photo_upload.img_src FROM photo_upload inner JOIN post_items ON post_items.photo_set_id = photo_upload.photo_set_id
WHERE post_items.photo_set_id = photo_upload.photo_set_id ");
//store the images in a separate array
$imgArray = array();
if ($stmt2->execute()) {
$photo_items = $stmt2->get_result();
while ($obj2 = $photo_items->fetch_object()) {
$imgArray[] = $obj2;
}
}
if($stmt->execute()){
$post_items = $stmt->get_result();
if(mysqli_num_rows($post_items) > 0){
while ($obj = $post_items->fetch_object()) {
$jsonData[] = $obj;
// check if there are any elements in the array
if(count($imgArray) > 0){
// set the img_src index of the jsonData array with the elements of the other array
$jsonData['img_src'] = $imgArray;
}
}
$i = json_encode($jsonData);
echo $i;
}
}