I have a JSON array inside which there are JSON Objects
like this:
[
{
"id": "63",
"userprofile": "userprofile.jpg",
"username": "James",
"content": "test.",
"address": "1111 Parker St",
"Post_date": "2022-05-25 02:41:15",
"images": [
"20220525_0241291.jpg",
"20220525_0241290.jpg"
]
}
]
I would like to have the string elements in the images
array as objects instead. Can anyone suggest me how to make this type of JSON?
[
{
"id": "63",
"userprofile": "userprofile.jpg",
"username": "James",
"content": "test.",
"address": "1111 Parker St",
"Post_date": "2022-05-25 02:41:15",
"images": [
{"image": "20220525_0241291.jpg"},
{"image": "20220525_0241290.jpg"}
]
}
]
Here is my PHP code
<?php
header("Content-Type:application/json");
include '../db_con.php';
$query = "SELECT Board.* ,
GROUP_CONCAT(Board_images.imagepath separator ',') AS multiimages
FROM Board
LEFT JOIN Board_images ON Board.index = Board_images.boardindex
GROUP BY Board.index
ORDER BY Board.index";
$result = mysqli_query($conn, $query);
$response = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push(
$response,
array(
'id' => $row['index'],
'userprofile' => $row['userprofile'],
'username' => $row['username'],
'content' => $row['content'],
'address' => $row['address'],
'Post_date' => $row['Post_date'],
'images' => explode(',',$row['multiimages'])
)
);
}
echo json_encode($response);
?>
CodePudding user response:
explode
returns a simple array of strings. All you have to do is go over it and put each of those strings into an array. You can do this in a loop or using an array function like array_map()
which will do the same thing, applying a callback to each item.
You also don't need a loop to populate your response array, instead use mysqli_result::fetch_all()
. You could use a loop to add the extra images
element, but again I prefer using the array_walk()
function as a matter of personal opinion.
(The difference between array_map
and array_walk
is that array_map
returns a new array based on what the callback returns. array_walk
only modifies the existing array.)
<?php
include '../db_con.php';
$query = "SELECT Board.* , GROUP_CONCAT(Board_images.imagepath separator ',') AS multiimages FROM Board
LEFT JOIN Board_images ON Board.index = Board_images.boardindex GROUP BY Board.index ORDER BY Board.index";
$result = $con->query($query);
// fetch all the records at once
$response = $result->fetch_all(\MYSQLI_ASSOC);
// this performs similar function to a foreach loop
array_walk(
$response,
function (&$v, $k) {
// explode the comma-separated list into an indexed array
$images = explode(",", $v["multiimages"]);
// now turn it into a bunch of associative arrays
$images = array_map(fn ($im) => ["image" => $im], $images);
// and then add it to the original $response array
$v["images"] = $images;
}
);
header("Content-Type:application/json");
echo json_encode($response);