remove unnecessary hierarchy from json output - php

I am building an admin backend for an android app. My code provides a json output which the android developer then uses in his app. The developer asked me if it is possible to reduce the hierarchy level in the json output
as in remove the highlighted []0 and put the contents directly inside the []data instead.
This is my current php code
if($type == 1 ) //Handle item display
{
try
{
$query = "SELECT category FROM category";
$result= $DBH->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'";
$value = $DBH->query($query1);
if($row1 = $value->fetchAll(PDO::FETCH_OBJ)){
$main[] = array('data'=>array($row1));
}
else
{
$main[] = array('data'=>array('catagory'=>$row['category']));
}
}
echo json_encode($main);
$result->closeCursor(); //Close database connection free resources
$DBH = null;
}
catch(PDOException $e){
print $e->getMessage ();
die();
}
}
And the json output being generated
[
{
"data": [
[
{
"id": "2",
"name": "rice",
"price": "20",
"description": "Plain Rice",
"image": "4106_rice.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
},
{
"id": "3",
"name": "item 1",
"price": "32",
"description": "item 1 description",
"image": "1370_2Ckjikljklkljh.jpg",
"time": "10",
"catagory": "Lunch",
"subcat": "Chicken Soup"
},
{
"id": "4",
"name": "hello",
"price": "10",
"description": "fgsdjfsfsdj",
"image": "",
"time": "76",
"catagory": "Lunch",
"subcat": ""
}
]
]
},
{
"data": {
"catagory": "Dinner"
}
},
{
"data": {
"catagory": "Soup"
}
},
{
"data": {
"catagory": "Test"
}
}
]
I am not very sure if I can make the changes he asked or if it is possible. Is it doable?

Your json structure is inconsistent and try this approach, will be easier for the developer to parse
{
"response": [
{
"data": [
{
"id": "2",
"name": "rice",
"price": "20",
"description": "Plain Rice",
"image": "4106_rice.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
},
{
"id": "3",
"name": "item 1",
"price": "32",
"description": "item 1 description",
"image": "1370_2Ckjikljklkljh.jpg",
"time": "10",
"catagory": "Lunch",
"subcat": "Chicken Soup"
},
{
"id": "4",
"name": "hello",
"price": "10",
"description": "fgsdjfsfsdj",
"image": "",
"time": "76",
"catagory": "Lunch",
"subcat": ""
}
]
},
{
"data": [
{
"catagory": "Dinner"
}
]
},
{
"data": [
{
"catagory": "Soup"
}
]
},
{
"data": [
{
"catagory": "Test"
}
]
}
]
}

Related

What is the most efficient way to change a list to a nested object in php

I have a list of (the result of a query in DB) like this:
[
{
"id": "1",
"parent_id": null,
"title": "مدادنوکی",
"url": "/medadnoki"
},
{
"id": "2",
"parent_id": null,
"title": "جامعه",
"url": "/commiunity"
},
{
"id": "5",
"parent_id": "1",
"title": "درباره ی مدادنوکی",
"url": "/about"
},
{
"id": "6",
"parent_id": "1",
"title": "درباره ی مدادنوکی",
"url": "/about"
},
{
"id": "7",
"parent_id": "2",
"title": "همکاران",
"url": "/co-worker"
},
{
"id": "8",
"parent_id": "2",
"title": "اساتید",
"url": "/masters"
}
]
But I want to create an object like this:
[
{
"title": "مدادنوکی",
"url": "/medadnoki",
"subs" : [
{
"title": "درباره مدادنوکی",
"url": "/about"
},
{
"title": "درباره مدادنوکی",
"url": "/about"
},
{
"title": "درباره مدادنوکی",
"url": "/about"
},
{
"title": "درباره مدادنوکی",
"url": "/about"
}
]
},
{
"title": "جامعه",
"url": "/soc",
"subs" : [
{
"title": "همکاران",
"url": "/co-work"
},
{
"title": "اساتید",
"url": "/masters"
}
]
}
]
I have handled this process with two foreach in php and it means I process data twice and it is not efficient and will be slow.
Is there any Idea to doing this with just one foreach?
using one foreach means faster than two foreach twice and It will show the result in big data
Assuming you have the results in an order where the parents appear in the results before any children they may have, this should work:
$nested = [];
foreach($results as $r) {
if($r['parent_id'] === null) {
$nested[$r['id']] = [
'title' => $r['title'],
'url' => $r['url'],
'subs' => []
];
continue;
}
$nested[$r['parent_id']]['subs'][] = [
'title' => $r['title'],
'url' => $r['url']
];
}
$nested = array_values($nested);

Display some parts of a file written in json

Below is my JSON file:
{
"example": "1",
"example2": 2,
"text": "3",
"info": {
"agent": 4,
"sum": 5,
"collection": [{
"Name": "6",
"Pic": "7"
} {
"Name": "8",
"Pic": "9"
}, {
"Name": "10",
"Pic": "11"
}]
}
}
How would I display each 'name' and 'pic' I think I need to use a foreach loop but don't know how to.
This is all the code I have:
$data = json_decode(file_get_contents('http://linktojson.com'));
echo $data['info']['collection'][0]['Name'];
echo $data['info']['collection'][0]['Pic'];
This should work
$data = json_decode(file_get_contents('http://linktojson.com'));
echo "<pre>".print_r($data,1)."</pre>";
foreach($data->info->collection as $key){
echo $key->Pic;
echo $key->Name;
}
Valid JSON
{
"example": "1",
"example2": 2,
"text": "3",
"info": {
"agent": 4,
"sum": 5,
"collection": [{
"Name": "6",
"Pic": "7"
}, {
"Name": "8",
"Pic": "9"
}, {
"Name": "10",
"Pic": "11"
}]
}
}

group elements inside a json

I'm trying to make a json that looks like this:
{
"data": {
"error_message": "",
"data": {
"person": [
[
{
"name": "teset1",
"image": "http://test.co.il/test/icons/billadress.png"
},
{
"name": "test2",
"image": "http://test.co.il/test/icons/email.png"
},
{
"name": "test3",
"image": "http://test.co.il/test/icons/homeicon.png"
}
],
[
{
"name": "a",
"image": "http://test.co.il/shay/keykit/icons/billadress.png"
},
{
"name": "b",
"image": "http://test.co.il/shay/keykit/icons/email.png"
},
{
"name": "c",
"image": "http://dvns.co.il/shay/keykit/icons/homeicon.png"
}
],
[
{
"name": "a",
"image": "http://test.co.il/test/icons/billadress.png"
},
{
"name": "b",
"image": "http://test.co.il/test/icons/email.png"
},
{
"name": "c",
"image": "http://dvns.co.il/test/icons/homeicon.png"
}
],
]
}
},
}
This is the code i'm using after i'm getting the name & image from the mysql query:
$response = $this->_db->query($query)->result_array();
$icons_results = array();
$obj = new stdclass();
foreach ($response as $key => $response) {
$icons_model = new icons_model();
$icons_model->init($response);
$obj->families[] = $icons_model;
}
return $obj;
SO .. this is what i'm getting:
{
"data": {
"families": [
{
"id": "1",
"name": "a",
"image_url": "http://test.co.il/shay/keykit/icons/billadress.png"
},
{
"id": "2",
"name": "b",
"image_url": "http://test.co.il/shay/keykit/icons/email.png"
},
{
"id": "3",
"name": "c",
"image_url": "http://test.co.il/test/icons/homeicon.png"
},
{
"id": "6",
"name": "f",
"image_url": "http://test.co.il/test/icons/homeicon.png"
},
{
"id": "4",
"name": "d",
"image_url": "http://test.co.il/test/icons/billadress.png"
},
{
"id": "5",
"name": "e",
"image_url": "http://test.co.il/test/icons/billadres2323s.png"
},
and do on.
How to i make that every three object will be in a group? (like the first example)
Try this:
foreach ($response as $key => $response) {
$icons_model = new icons_model();
$icons_model->init($response);
$obj->families[(int)($key / 3)][] = $icons_model;
}

JSON decoding array

I have this JSON code:
{
"phrases": [
{
"phrases": [
{
"id": "33",
"text": "sasdsad",
"date": "2012-03-14 20:28:45",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
},
{
"id": "32",
"text": "que ondaa\r\n",
"date": "2012-03-14 20:27:45",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
},
{
"id": "31",
"text": "dsadssadsad",
"date": "2012-03-14 20:27:35",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
}
],
"details": {
"success": "true",
"phrase_id": "",
"phrase_text": "",
"phrase_date": ""
}
}
I don't really know what to do. I get some phrases vía MySQL, and pushes them to an array. This array is json_encoded() and gets printed.
$sth = $sql;
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
$sth = $sql;
$data = array(
"success" => "true",
"phrase_id" => "",
"phrase_text" => "",
"phrase_date" => "",
);
print json_encode($rows).json_encode($data);
and with jQuery I was trying to parse it, but I can't. This is the main problem.
function getPhrases(order,limit,last){
var req_url = ...;
$.getJSON(req_url, function(data) {
$.each(data.phrases, function(i, data) {
appendPhrase(data.text);
lastid = data.id;
});
$.each(data.details, function(i, data) {
$("#phrases-count").html(data.totalcount);
});
});
}
PS: I was doing this with "echo" but got some problems.
{
"phrases": [
{
"id": "33",
"text": "sasdsad",
"date": "2012-03-14 20:28:45",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
},
{
"id": "32",
"text": "que ondaa<br />",
"date": "2012-03-14 20:27:45",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
},
{
"id": "31",
"text": "dsadssadsad",
"date": "2012-03-14 20:27:35",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
}
],
"details": [
{
"totalcount": "3",
"logged_in": "false"
}
]
}
You can't simply combine these JSON arrays:
print json_encode($rows).json_encode($data);
Try this (attempt 2):
print json_encode( array('phrases' => $rows, 'details' => $data) );

PHP Troubles with converting from JSON to stdClass, making changes, and then converting back to JSON

So, in the very beginning, before the send_sms.php is loaded, I have this Json stored in a database:
{
"chats": {
"chat": [{
"id": "1",
"name": "Ethan Wilberforce",
"messages": {
"message": [{
"id": "1",
"name": "Ethan Wilberforce",
"text": "Hello how are you doing",
"time": "4:41"
}, {
"id": "2",
"name": "Qasim Iqbal",
"text": "Not bad. How about you?",
"time": "4:42"
}, {
"id": "3",
"name": "Ethan Wilberforce",
"text": "I'm not too bad myself.",
"time": "4:43"
}]
}
}, {
"id": "2",
"name": "Geoff Vahaaho",
"messages": {
"message": [{
"id": "1",
"name": "Geoff Vahaaho",
"text": "Hello how are you doing",
"time": "4:41"
}, {
"id": "2",
"name": "Qasim Iqbal",
"text": "Not bad. How about you?",
"time": "4:42"
}, {
"id": "3",
"name": "Geoff Vahaaho",
"text": "I'm not too bad myself.",
"time": "4:43"
}, {
"id": "4",
"name": "Qasim Iqbal",
"text": "Nice.",
"time": "4:43"
}]
}
}]
}
}
The Json is completely valid, no errors. It is storing two chats, with messages in them.
Now, here is the PHP code that alters the Json:
$data = $user->data;
$parsed_data = json_decode($data);
...
for($i = 0, $size = sizeof($parsed_data->chats->chat); $i < $size; ++$i) {
if($parsed_data->chats->chat[$i]->name == $to) {
$found = true;
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)] = new stdClass;
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)]->id = sizeof($parsed_data->chats->chat[$i]->messages->message);
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)]->name = $user->name;
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)]->text = $message;
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)]->time = $time;
echo "done. ";
break;
}
}
What I intend this to do is, to add another stdClass object in the "message" array of the chat. So I basically do just that, hoping it will work.
Now, it works, kind of, but here is the new Json after we json_encode it:
{
"chats": {
"chat": [{
"id": "1",
"name": "Ethan Wilberforce",
"messages": {
"message": [{
"id": "1",
"name": "Ethan Wilberforce",
"text": "Hello how are you doing",
"time": "4:41"
}, {
"id": "2",
"name": "Qasim Iqbal",
"text": "Not bad. How about you?",
"time": "4:42"
}, {
"id": "3",
"name": "Ethan Wilberforce",
"text": "I'm not too bad myself.",
"time": "4:43"
}, {}, {
"id": 4
}, {
"name": "Qasim Iqbal"
}, {
"text": "Hello i am testing"
}, {
"time": 1326066200
}]
}
}, {
"id": "2",
"name": "Geoff Vahaaho",
"messages": {
"message": [{
"id": "1",
"name": "Geoff Vahaaho",
"text": "Hello how are you doing",
"time": "4:41"
}, {
"id": "2",
"name": "Qasim Iqbal",
"text": "Not bad. How about you?",
"time": "4:42"
}, {
"id": "3",
"name": "Geoff Vahaaho",
"text": "I'm not too bad myself.",
"time": "4:43"
}, {
"id": "4",
"name": "Qasim Iqbal",
"text": "Nice.",
"time": "4:43"
}]
}
}]
}
}
You will notice it was indeed added in the "Ethan Wilberforce" chat, but each string in the stdClass was converted to its own array item in the "message" array. How could I fix this problem? Many thanks.
Your problem is this:
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)] = new stdClass;
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)]->id = sizeof($parsed_data->chats->chat[$i]->messages->message);
It basically amounts to:
$array[$last] = new stdClass();
$array[$last+1] = "id";
$array[$last+2] = "name";
You keep appending new arrays/objects, because you use sizeof(...) which always becomes one larger than the previous line. It's not the last index, but the size. Which is $lastindex+1.
What you should be doing anyway, is not using an object, but just appending an array, and with all its attributes at once:
$parsed_data->chats->chat[$i]->messages->message[] = array(
"id" => ...,
"name" => ...,
"time" => ...,
);
When you encode that associative array back into JSON it will also become a normal {...} JSON object group.

Categories