php JSON data structure for angular app - php

I am trying to format the a mysql response into a array of objects so that Angular can easily traverse the data.
mysql result:
[{
"FIAccountsID": "99",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "1"
},
{
"FIAccountsID": "99",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "2"
},
{
"FIAccountsID": "100",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "1"
},
{
"FIAccountsID": "100",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "2"
},
{
"FIAccountsID": "101",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "1"
},
{
"FIAccountsID": "101",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "2"
},
{
"FIAccountsID": "102",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "1"
},
{
"FIAccountsID": "102",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "2"
},
{
"FIAccountsID": "103",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "1"
},
{
"FIAccountsID": "103",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "2"
}......
here it the PHP:
while($row = mysqli_fetch_assoc($result))
{
$uid = $row['UserID'];
$name = $row['FirstName'].' '.$row['LastName'];
$fiid = $row['FinancialInstID'];
$fi = $row['FinancialInstName'];
$acctID = $row['FIAccountsID'];
$rows[$uid]['name'] = $name;
$rows[$uid]['uid'] = $uid;
$rows[$uid]['fi'][$fiid]['name'] = $fi;
$rows[$uid]['fi'][$fiid]['acct'][$acctID]['name'] = $row['AccountCustomName'];
}
print json_encode($rows);
this is what i get:
{
"1": {
"name": "Some Name",
"uid": "1",
"fi": {
"9": {
"name": "Testes",
"accts": {
"99": {
"name": "name 1"
},
"100": {
"name": "name 2"
},
"103": {
"name": "name 3"
}
}
}
}
},
"2": {
"name": "Another Name",
"uid": "2",
"fi": {
"7": {
"name": "Trevor's Brokerage House",
"accts": {
"1": {
"name": "Sally's 401k Account"
},
"2": {
"name": "retirement"
},
"3": {
"name": "Some other account"
..........
desired result:
[
{
"users": [
{
"name": "Some Name",
"uid": "1",
"fi": [
{
"name": "Testes",
"acct": [
{
"name": "name 1"
},
{
"name": "name 2"
},
{
"name": "name 3"
}
]
}
]
},
{
"name": "Another Name",
"uid": "2",
"fi": [
{
"name": "Trevor's Brokerage House",
"acct": [
{
"name": "Sally's 401k Account"
},
{
"name": "retirement"
},
{
"name": "Some other account"
..........
I want to know how to have the data structure without the unique keys prefixing the nested arrays

The thing is that if you define keys, json_encode will read them. If you don't want keys, declare the array without them. So, what you need to do is to structure your array according to you desired output.
But the way your data is arranged make it somewhat hard to format it properly. The solution I can see is to do what you're already doing:
while($row = mysqli_fetch_assoc($result))
{
$uid = $row['UserID'];
$name = $row['FirstName'].' '.$row['LastName'];
$fiid = $row['FinancialInstID'];
$fi = $row['FinancialInstName'];
$acctID = $row['FIAccountsID'];
$rows[$uid]['name'] = $name;
$rows[$uid]['uid'] = $uid;
$rows[$uid]['fi'][$fiid]['name'] = $fi;
$rows[$uid]['fi'][$fiid]['acct'][$acctID]['name'] = $row['AccountCustomName'];
}
But then you revisit the array and remove all the keys using array_values:
foreach ($rows as $uid => $data)
{
foreach ($data['fi'] as $fiid => $fi)
{
$rows[$uid]['fi'][$fiid]['acct'] = array_values($fi['acct']);
}
$rows[$uid]['fi'] = array_values($rows[$uid]['fi']);
}
// Here you format the outer array:
$rows = array(array('users' => array_values($rows)));
Which gives a result like this:
[
{
"users": [
{
"name": "Someones Name",
"uid": "1",
"fi": [
{
"name": "Testes",
"acct": [
{
"name": "Brothers"
},
{
"name": "Brothers"
},
{
"name": "Brothers"
},
{
"name": "Brothers"
},
{
"name": "Brothers"
}
]
}
]
},
{
"name": "Someones Name",
"uid": "2",
"fi": [
{
"name": "Testes",
"acct": [
{
"name": "Brothers"
},
{
"name": "Brothers"
}
]
}
]
}
]
}
]

Related

Sorting only a part of object/array in PHP

I've been struggling around this for a while now and can't seem to get the right algorithm.
What I want is to sort this:
$variable = '{
"0": {
"id": "0",
"code": "main_colour",
"label": "Main Colour",
"options": [{
"id": "825",
"label": "White",
"products": ["1", "2", "3"]
}, {
"id": "840",
"label": "Cream",
"products": ["3", "4", "5"]
}],
"position": "0"
},
"2": {
"id": "0",
"code": "size",
"label": "Size",
"options": [{
"id": "825",
"label": "S",
"products": ["1", "2", "3"]
}, {
"id": "840",
"label": "M",
"products": ["3", "4", "5"]
}],
"position": "0"
}
}';
And the output would be
$variable = '{
"0": {
"id": "0",
"code": "main_colour",
"label": "Main Colour",
"options": [{
"id": "840",
"label": "Cream",
"products": ["3", "4", "5"]
},{
"id": "825",
"label": "White",
"products": ["1", "2", "3"]
}],
"position": "0"
},
"2": {
"id": "0",
"code": "size",
"label": "Size",
"options": [{
"id": "840",
"label": "M",
"products": ["3", "4", "5"]
}, {
"id": "825",
"label": "S",
"products": ["1", "2", "3"]
}],
"position": "0"
}
}';
So basically it should be sorted using the label inside the "options" without affecting the other fields. I've been trying usort and tried different algorithms but to no avail.
Current code that sorts only the outside "label" and not the inner label:
function optionsSort($a, $b) {
return strcmp($a['options'][0]['label'], $b['options'][0]['options']['label']);
}
usort($variable, "optionsSort"));
Here's the code:
// your array
$variable = '{
"0": {
"id": "0",
"code": "main_colour",
"label": "Main Colour",
"options": [{
"id": "825",
"label": "White",
"products": ["1", "2", "3"]
}, {
"id": "840",
"label": "Cream",
"products": ["3", "4", "5"]
}],
"position": "0"
},
"2": {
"id": "0",
"code": "size",
"label": "Size",
"options": [{
"id": "825",
"label": "S",
"products": ["1", "2", "3"]
}, {
"id": "840",
"label": "M",
"products": ["3", "4", "5"]
}],
"position": "0"
}
}';
$a = json_decode($variable);
foreach ($a as $item) {
// sorting function
usort($item->options, function($a, $b) { return strcmp($a->label, $b->label); });
}

How to show one array in another array in php?

I have table of a survey,answer and user. Answer and survey table is linked by user_id also user and survey is linked with user_id.
I want to show answers and user and comment for a survey. comment is inside survey table.
I want to get the result in this format:
{
result:1,
message:'success',
survey:[
{
answers:
[
],
user:
{
}
comment:
},
{
answers:
[
],
user:
{
}
comment:
}
]
}
getAllSurveyByDoctor function:
function getAllSurveyByDoctor($user_id)
{
$database = new SurveyDatabase(SurveyConstants::DBHOST,SurveyConstants::DBUSER,SurveyConstants::DBPASS,SurveyConstants::DBNAME);
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("SELECT * from survey where `user_id` = ?");
$stmt->execute(array($user_id));
$survey = $stmt->fetchAll(PDO::FETCH_ASSOC);
$surveys = array();
$answers = array();
if (count($survey) > 0) {
foreach($survey as $row)
{
$stmt = $dbConnection->prepare("SELECT answer.answer_id, answer.survey_id, answer.question_id, answer.rating, answer.user_id, question.question_id, question.question, question.type FROM `answer` INNER JOIN `question` ON
answer.question_id = question.question_id WHERE answer.user_id = ? and answer.survey_id = ?");
$s_id = $row['survey_id'];
$stmt->execute(array($user_id,$s_id));
$answer = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $dbConnection->prepare("SELECT users.user_id,users.email_id,users.pass,users.address,users.name,survey.survey_id,survey.user_id FROM `users` INNER JOIN `survey` ON users.user_id = survey.user_id WHERE users.user_id = ?");
$stmt->execute(array($user_id));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$comment = $row['comment'];
// $surveys[] = $row;
$answers = $answer;
$surveys[] = $answers;
$surveys[] = $user;
$surveys[] = $comment;
}
$response = array("status" => 1, "message" => "Success", "surveys" => $surveys);
return json_encode($response);
}
else {
$response = array("status"=>-1,"message"=>"surveys list is empty");
return json_encode($response);
}
}
I get the result like this:
{
"status": 1,
"message": "Success",
"surveys": [
[
{
"answer_id": "50",
"survey_id": "35",
"question_id": "1",
"rating": "4",
"user_id": "9",
"question": "Scheduling appointments",
"type": "rating"
},
{
"answer_id": "51",
"survey_id": "35",
"question_id": "2",
"rating": "6",
"user_id": "9",
"question": "Office environment",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"0",
[],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"0",
[
{
"answer_id": "54",
"survey_id": "37",
"question_id": "1",
"rating": "4",
"user_id": "9",
"question": "Scheduling appointments",
"type": "rating"
},
{
"answer_id": "55",
"survey_id": "37",
"question_id": "2",
"rating": "6",
"user_id": "9",
"question": "Office environment",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"0",
[],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"csdcs",
[
{
"answer_id": "72",
"survey_id": "49",
"question_id": "7",
"rating": "5",
"user_id": "9",
"question": "Doctor listens and answers questions",
"type": "rating"
},
{
"answer_id": "73",
"survey_id": "49",
"question_id": "6",
"rating": "5",
"user_id": "9",
"question": "Doctor explains medical condition(s)",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"",
[
{
"answer_id": "74",
"survey_id": "50",
"question_id": "8",
"rating": "5",
"user_id": "9",
"question": "Doctor spends enough time with patients",
"type": "rating"
},
{
"answer_id": "75",
"survey_id": "50",
"question_id": "3",
"rating": "5",
"user_id": "9",
"question": "Staff helpfulness",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"",
[
{
"answer_id": "76",
"survey_id": "51",
"question_id": "7",
"rating": "5",
"user_id": "9",
"question": "Doctor listens and answers questions",
"type": "rating"
},
{
"answer_id": "77",
"survey_id": "51",
"question_id": "6",
"rating": "5",
"user_id": "9",
"question": "Doctor explains medical condition(s)",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"",
[
{
"answer_id": "78",
"survey_id": "52",
"question_id": "8",
"rating": "5",
"user_id": "9",
"question": "Doctor spends enough time with patients",
"type": "rating"
},
{
"answer_id": "79",
"survey_id": "52",
"question_id": "5",
"rating": "5",
"user_id": "9",
"question": "Trust in doctor's decision",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"",
[
{
"answer_id": "80",
"survey_id": "53",
"question_id": "1",
"rating": "5",
"user_id": "9",
"question": "Scheduling appointments",
"type": "rating"
},
{
"answer_id": "81",
"survey_id": "53",
"question_id": "7",
"rating": "5",
"user_id": "9",
"question": "Doctor listens and answers questions",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"",
[
{
"answer_id": "82",
"survey_id": "54",
"question_id": "6",
"rating": "5",
"user_id": "9",
"question": "Doctor explains medical condition(s)",
"type": "rating"
},
{
"answer_id": "83",
"survey_id": "54",
"question_id": "3",
"rating": "5",
"user_id": "9",
"question": "Staff helpfulness",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
""
]
}
I am getting some what format same as I want. I am getting answers array, user and comment after that. But how I can name it? Can not identify from this result that where are answers, user and comment. I want to name it. How can I? Thank you.
You can simply create an associative array for each survey. Inside this associative array, assign your keys and your values. Here's how it looks :
function getAllSurveyByDoctor($user_id)
{
$database = new SurveyDatabase(SurveyConstants::DBHOST,SurveyConstants::DBUSER,SurveyConstants::DBPASS,SurveyConstants::DBNAME);
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("SELECT * from survey where `user_id` = ?");
$stmt->execute(array($user_id));
$survey = $stmt->fetchAll(PDO::FETCH_ASSOC);
$surveys = array();
$answers = array();
if (count($survey) > 0) {
foreach($survey as $row)
{
$stmt = $dbConnection->prepare("SELECT answer.answer_id, answer.survey_id, answer.question_id, answer.rating, answer.user_id, question.question_id, question.question, question.type FROM `answer` INNER JOIN `question` ON
answer.question_id = question.question_id WHERE answer.user_id = ? and answer.survey_id = ?");
$s_id = $row['survey_id'];
$stmt->execute(array($user_id,$s_id));
$answer = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $dbConnection->prepare("SELECT users.user_id,users.email_id,users.pass,users.address,users.name,survey.survey_id,survey.user_id FROM `users` INNER JOIN `survey` ON users.user_id = survey.user_id WHERE users.user_id = ?");
$stmt->execute(array($user_id));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$comment = $row['comment'];
// $surveys[] = $row;
//We create the "survey" associative array
$survey = [];
$answers = $answer;
$survey['answers']= $answers;
$survey['user'] = $user;
$survey['comment']=$comment;
//We add the survey array to the survey
$surveys[] = $survey;
}
$response = array("status" => 1, "message" => "Success", "surveys" => $surveys);
return json_encode($response);
}
else {
$response = array("status"=>-1,"message"=>"surveys list is empty");
return json_encode($response);
}
}

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;
}

How to access the JSON's multi-level objects with jQuery [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
In CodeIgniter, in PHP to create a nested-like elements for dropdown <select> I'am using this function:
function list_categories(&$result, $cats, $sub = ''){ // <- THIS
foreach($cats as $cat){
//$cat['category']->id = $sub.$cat['category']->title;
$result[$cat['category']->id] = $sub.$cat['category']->title; // <- THIS
if( sizeof($cat['children']) > 0 ){
$sub2 = str_replace('—→ ', '–', $sub);
$sub2.= '–→ ';
list_categories($result, $cat['children'], $sub2); // <- THIS
}
}
}
// Make an array available outside the function
$categoryData = array(0 => '-- '.lang('FORM_SELECT_CATTOP').' --');
// Launch the function to fill out the array with nested sets
list_categories($categoryData, $categories);
Which generates the HTML <select> list:
I want to do the same from retrieved JSON in jQuery but can't find the answer to go deeper than first level of JSON objects with this jQuery function:
$.getJSON('../raw_get_categories/'+com_id_selected+'/0', function(data){
var items = [];
$.each(data, function(key, value, sub){
items.push('<option id="'+ key[0] + '">' + value[0] + '</option>');
});
console.log(items);
});
And this is the JSON I want to manage and retrieve the same values from it like in PHP code:
{
"28": {
"category": {
"id": "28", // <<< I need to retrieve THIS
"pid": "0",
"com_id": "2",
"route_id": "59",
"excerpt": "",
"ordering": "1",
"title": "Oblecenie a vybava",
"slug": "oblecenie-a-vybava1",
"description": "",
"image": "clothes.png",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": {
"61": {
"category": {
"id": "61", // <<< I need to retrieve THIS
"pid": "28",
"com_id": "2",
"route_id": "52",
"excerpt": "",
"ordering": "1",
"title": "Ubor na hlavu",
"slug": "ubor-na-hlavu1",
"description": "<p>Capice, Klobuky, Panamy, Baretky, Prilby, Kukly<br></p>",
"image": "clothes-head.png",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
},
"30": {
"category": {
"id": "30",
"pid": "28",
"com_id": "2",
"route_id": "53",
"excerpt": "",
"ordering": "2",
"title": "Bundy a vetrovky",
"slug": "bundy-a-vetrovky",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": {
"34": {
"category": {
"id": "34",
"pid": "30",
"com_id": "2",
"route_id": "0",
"excerpt": "",
"ordering": "0",
"title": "Letne",
"slug": "letne",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
},
"35": {
"category": {
"id": "35",
"pid": "30",
"com_id": "2",
"route_id": "0",
"excerpt": "",
"ordering": "0",
"title": "Vsesezonne",
"slug": "vsesezonne",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
},
"33": {
"category": {
"id": "33",
"pid": "30",
"com_id": "2",
"route_id": "0",
"excerpt": "",
"ordering": "0",
"title": "Zimne",
"slug": "zimne",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
}
}
},
"31": {
"category": {
"id": "31",
"pid": "28",
"com_id": "2",
"route_id": "54",
"excerpt": "",
"ordering": "3",
"title": "Nohavice a teplaky",
"slug": "nohavice-a-teplaky",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
},
"32": {
"category": {
"id": "32",
"pid": "28",
"com_id": "2",
"route_id": "55",
"excerpt": "",
"ordering": "4",
"title": "Obuv",
"slug": "obuv",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
}
}
},
"38": {
...
}
Could someone suggest me the appropriate way to achieve the same foreach statement in jQuery pls?
Juste use point to get more childs
$.getJSON('filename.php', function(data) {
$('#List li').remove();
$.each(data, function(index, item) {
$('#list').append('<li>'+item.category.id+'</li>');
});
});
You can do something like this:
$.each(data.actions, function(entryIndex, entry) {
var html = '<li class="top-level">' + this.action + '</li>';
});
Source

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

Categories