John Davidson

arrays - Manipulate PHP stdClass output to have desired json format

0 comments
Message:


I am getting dataset from a database query as object. What I want to do is to manipulate current output and create an additional array to store some of the output to have it compatible for my json input in another call.


Current json_encode($myObj) output


[
{
"entry": "10",
"displayid": "100",
"folder": "1"
},
{
"entry": "20",
"displayid": "200",
"folder": "2"
},
{
"entry": "30",
"displayid": "300",
"folder": "3"
}
]

What I am trying to have through this data is;


[
{
"file": {
"entry": 10,
"displayid": 100
},
"folder": 1
},
{
"file": {
"entry": 20,
"displayid": 200
},
"folder": 2
},
{
"file": {
"entry": 30,
"displayid": 300
},
"folder": 3
}
]

I tried the following, but it gives me completely weird output;


foreach ($result as $res) {
$ho = new stdClass();
$ho->file = [$ho->entry = $res->entry, $ho->displayid = $res->displayid];
$ho->folder = $res->folder;
}


My Answer:
"id": 1,
"name": "John Doe",
"age": 30
},
{
"id": 2,
"name": "Jane Smith",
"age": 25
}
]

_Desired output_

{
"data": [
{
"id": 1,
"name": "John Doe"
},
{
"id": 2,
"name": "Jane Smith"
}
]
}

php
// Assuming $myObj is the stdClass object obtained from the database query

$newObj = new stdClass();
$newObj->data = [];

foreach ($myObj as $item) {
$newItem = new stdClass();
$newItem->id = $item->id;
$newItem->name = $item->name;

$newObj->data[] = $newItem;
}

echo json_encode($newObj);

Rate this post

5 of 5 based on 2727 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us