How can I access index with # in json - php

I need to get properties from this "#attributes"
{
"#attributes": {
"docid": "1082530207018916577"
},
"track": [
{
"#attributes": {
"id": "0",
"name": "",
"lang_code": "da",
"lang_original": "Dansk",
"lang_translated": "Danish"
}
},
{
"#attributes": {
"id": "5",
"name": "",
"lang_code": "nl-BE",
"lang_original": "Nederlands (België)",
"lang_translated": "Dutch (Belgium)"
}
},
{
"#attributes": {
"id": "2",
"name": "",
"lang_code": "en-GB",
"lang_original": "English (United Kingdom)",
"lang_translated": "English (United Kingdom)",
"lang_default": "true"
}
},
{
"#attributes": {
"id": "1",
"name": "",
"lang_code": "de-DE",
"lang_original": "Deutsch (Deutschland)",
"lang_translated": "German (Germany)"
}
},
{
"#attributes": {
"id": "4",
"name": "",
"lang_code": "id",
"lang_original": "Indonesia",
"lang_translated": "Indonesian"
}
},
{
"#attributes": {
"id": "6",
"name": "",
"lang_code": "pl",
"lang_original": "Polski",
"lang_translated": "Polish"
}
},
{
"#attributes": {
"id": "7",
"name": "",
"lang_code": "pt-BR",
"lang_original": "Português (Brasil)",
"lang_translated": "Portuguese (Brazil)"
}
},
{
"#attributes": {
"id": "3",
"name": "",
"lang_code": "es-419",
"lang_original": "Español (Latinoamérica)",
"lang_translated": "Spanish (Latin America)"
}
},
{
"#attributes": {
"id": "8",
"name": "",
"lang_code": "sv",
"lang_original": "Svenska",
"lang_translated": "Swedish"
}
}
]
}
My code:
$xml = simplexml_load_file('http://video.google.com/timedtext?type=list&v='.$video->id_youtube);
$json = json_encode($xml);
$result_array = json_decode($json, TRUE);
$res = "";
foreach ($result_array['track']['#attributes'] as $track) {
$res .= $track['lang_code'].'<br>';
}
return $res;
PHP or maybe Laravel is not recognizing the index "#attributes", reporting:
Undefined index: #attributes
How can I get the lang_codes?

$result_array['track'] is an array of objects.
You have to do
foreach($result_array['track'] as $track) {
$track = (array)$track;
$res .= $track['#attributes']['lang_code'].'<br>';
}

Related

Arrange JSON data saving duplicates into one row

Good morning guys!
I'm having a hard time trying to figure out how to arrange the following JSON:
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor's Degree"
}]
}
Into this:
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology", "Bachelor in Sociology",
"Number": "53","109",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}]
}
Basically, put the same degrees in one place and have all the names of said degree separated by a comma
I already have this JSON decoded into a variable:
$data = json_decode($topDegrees[1]["diplomas"],true);
Thanks in advance for your help!
I came up with this
$json = <<<JSON
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor's Degree"
}]
}
JSON;
$data = json_decode( $json, true );
$degrees = $data['degrees'];
$names = array_column($degrees, 'degree');
$count = array_count_values($names);
$duplicates = array_filter($count, function($var) {
return $var > 1;
});
foreach ( array_flip($duplicates) as $degree ) {
$filter = array_filter($degrees, function($var) use ($degree) {
return ( $var['degree'] === $degree );
});
$names = [];
$numers = [];
foreach ( $filter as $item ) {
$names[] = $item['Name'];
$numbers[] = $item['Number'];
}
$indices = array_keys($filter);
$index = array_shift($indices);
$degrees[$index]['Name'] = $names; // = join(', ', $names);
$degrees[$index]['Number'] = $numbers; // = join(', ', $numbers);
while ( count($indices) ) {
unset($degrees[array_shift($indices)]);
}
}
$data['degrees'] = $degrees;
print_r(json_encode($data));
// {"showElement":"1","degrees":[{"Name":["Bachelor in Psychology","Bachelor in Sociology"],"Number":["53","109"],"degree":"Bachelor's Degree"},{"Name":"Certificate","Number":"56","degree":"Certificate"},{"Name":"High School Diploma","Number":"28","degree":"High School"}]}
Your wanted json output is not valid, i have made an array structure in its place. If you want comma separated text, just use the join statements I've commented out.
$str = '{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor\'s Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor\'s Degree"
}]
}';
$str_arr = json_decode($str);
foreach($str_arr->degrees as $k=>$val){
if($val->degree == 'Bachelor\'s Degree'){
$new['Bachelor'][] = $val;
}else{
$new[] = $val;
}
}
foreach($new['Bachelor'] as $aa){
$nameStr[]= $aa->Name;
$numStr[] = $aa->Number;
}
$nameStr = implode(', ', $nameStr);
$numStr = implode(', ', $numStr);
$degree = 'Bachelor\'s Degree';
$new[] = (object) array($nameStr, $numStr, $degree);
unset($new['Bachelor']);
echo $json = json_encode($new);
echo "<pre>"; print_r(json_decode($json));
Hope this helps.
Demo here
This should do it:
<?php
$json = '{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelors Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelors Degree"
}]
}';
$items = json_decode($json, true);
$orderedItems = [];
$final = ['showElement' => 1];
foreach ($items['degrees'] as $item) {
$orderedItems[$item['degree']]['Name'][] = $item['Name'];
$orderedItems[$item['degree']]['Number'][] = $item['Number'];
$orderedItems[$item['degree']]['degree'] = $item['degree'];
}
foreach ($orderedItems as $order) {
$order['Name'] = (count($order['Name']) > 1) ? $order['Name'] : $order['Name'][0];
$order['Number'] = (count($order['Number']) > 1) ? $order['Number'] : $order['Number'][0];
$final['degrees'][] = [
'Name' => $order['Name'],
'Number' => $order['Number'],
'degree' => $order['degree']
];
}
echo json_encode($final);

Parsing an array with PHP in a foreach loop

I want to parse an array with PHP's foreach loop to get the object names and values inside the 'ques' array.
[
{
"ques": [
{
"name": "comment",
"value": "comment me for the reason",
"sur_id": "1",
"user_id": "admin#gmail.com",
"pagename": "question_response"
},
{
"name": "check-box[]",
"value": "1"
},
{
"name": "radio",
"value": "radio 2"
},
{
"name": "yes",
"value": "no"
}
]
"ques":[
{
"name": "date",
"value": "2015-10-23"
},
{
"name": "select-deopdown",
"value": ""
},
{
"name": "true",
"value": "false"
},
{
"name": "number",
"value": "55"
}
]
}
]
I want to separate the value from the 'ques' array:
while ($fetch = mysql_fetch_array($query1)) {
$content = $fetch['CONTENT_VALUES'];
// print_r($content);
$content_value= mb_convert_encoding($content ,"UTF-8");
$datas = json_decode($content, true);
foreach($datas->ques as $values)
{
echo $values->value . "\n";
print_r($values);
}
$test[] = array('ques' => $datas ,'answer'=>$values);
}

remove unnecessary hierarchy from json output

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"
}
]
}
]
}

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