How to make output json array with php? - php

I had searched the answer but there's no solution for my problem.
How make output like this?
Thanks in advance
I want out this below
Title: First Title
Tags: tag-a-1, tag-a-2,tag-a-3
Title: Second Title
Tags: tag-b-1, tag-b-2, tag-b-3
Title: Third Title
Tags: tag-c-1, tag-c-2, tag-c-3
file.json
{
"videos": [
{
"title": "First Title",
"tags": [
{
"tag_name": "tag-a-1"
},
{
"tag_name": "tag-a-2"
},
{
"tag_name": "tag-a-3"
}
],
"publish_date": "2016-09-12 16:40:14"
},
{
"title": "Second Title",
"tags": [
{
"tag_name": "tag-b-1"
},
{
"tag_name": "tag-b-2"
},
{
"tag_name": "tag-b-3"
}
],
"publish_date": "2016-09-12 16:40:14"
},
{
"title": "Third Title",
"tags": [
{
"tag_name": "tag-c-1"
},
{
"tag_name": "tag-c-2"
},
{
"tag_name": "tag-c-3"
}
],
"publish_date": "2016-09-12 16:40:14"
}
]
}
output.php
<?php
ini_set('display_errors', 1);
$html = "file.json";
$html = file_get_contents($html);
$videos = json_decode($html, true);
foreach ($videos['videos'] as $video) {
$title = $video['title'];
foreach ($video['tags'] as $tags) {
$tags = $tags['tag_name'];
echo 'Title: ' . $title . '<br />';
echo 'Tags: ' . $tags . ', <br /><br />';
}
}

Your second iteration seems to be wrong. You should print title/tags in your first loop instead.
foreach ($videos['videos'] as $video) {
$title = $video['title'];
$tags = array(); // reset it every new item to avoid race-condition on empty one.
foreach ($video['tags'] as $tags) {
$tags[] = $tags['tag_name'];
// ^ also add new elements here
}
echo 'Title: ' . $title . '<br />';
echo 'Tags: ' . implode(',', $tags) . '<br /><br />';
// ^ also join your tags
}

Try using the json_decode function. That seems the way to go.
http://php.net/manual/en/function.json-decode.php
I've linked the docs in for you. Best of luck.

Related

How to convert JSON to HTML using PHP?

I am trying to do the inverse function of the response received in this post: [Post][1]
[1]: https://stackoverflow.com/a/23427469/19867306
#scozy shows us a function to transform an html text to a JSON model. I need to transform the same JSON model to HTML again.
The function shared by #scozy is:
function html_to_obj($html) {
$dom = new DOMDocument();
$dom->loadHTML($html);
return element_to_obj($dom->documentElement);
}
function element_to_obj($element) {
$obj = array( "tag" => $element->tagName );
foreach ($element->attributes as $attribute) {
$obj[$attribute->name] = $attribute->value;
}
foreach ($element->childNodes as $subElement) {
if ($subElement->nodeType == XML_TEXT_NODE) {
$obj["html"] = $subElement->wholeText;
}
else {
$obj["children"][] = element_to_obj($subElement);
}
}
return $obj;
}
$html = <<<EOF
<!DOCTYPE html>
<html lang="en">
<head>
<title> This is a test </title>
</head>
<body>
<h1> Is this working? </h1>
<ul>
<li> Yes </li>
<li> No </li>
</ul>
</body>
</html>
EOF;
header("Content-Type: text/plain");
echo json_encode(html_to_obj($html), JSON_PRETTY_PRINT);
The output of the function is this:
{
"tag": "html",
"lang": "en",
"children": [
{
"tag": "head",
"children": [
{
"tag": "title",
"html": " This is a test "
}
]
},
{
"tag": "body",
"html": " \n ",
"children": [
{
"tag": "h1",
"html": " Is this working? "
},
{
"tag": "ul",
"children": [
{
"tag": "li",
"html": " Yes "
},
{
"tag": "li",
"html": " No "
}
],
"html": "\n "
}
]
}
]
}
I was thinking of making a function that, using the help of json_decode, transforms the json into an object and then makes use of a foreach and then makes a recursive call to the same function. At the moment my mind is all mixed up and it would be a great help if you could give me a hand.
My mind:
function json_to_html($json) {
$html = json_decode($json);
foreach ($html as $key => $item) {
// Something :C
}
}
$json = '{ "tag": "html", "lang": "en", "html": "\r\n", "children": [ { "tag": "head", "html": "\r\n ", "children": [ { "tag": "title", "html": " This is a test " } ] }, { "tag": "body", "html": "\r\n ", "children": [ { "tag": "h1", "html": " Is this working? " }, { "tag": "ul", "html": "\r\n ", "children": [ { "tag": "li", "html": " Yes " }, { "tag": "li", "html": " No " } ] } ] } ] }';
json_to_html($json);
I solved the question as follow:
function json_to_html($json) {
$html = "";
$param = "";
foreach ($json as $key => $value) {
if (is_numeric($key) || $key == 'children') {
$html = $html . json_to_html($value);
} else {
if ($key == 'tag') {
$tag = "<$value [param]>[html]</$value>";
continue;
} else if ($key == 'html') {
$tag = str_replace('[param]',$param,$tag);
$html = str_replace('[html]',$value,$tag);
continue;
} else {
$param = $param . $key . ' = "' . $value . '"';
continue;
}
}
}
return $html;
}
Note: the json is decoded previously

Count amount of elements from nested array

In the for loop I am trying to count the amount of flights in a nested array decoded from a JSON feed. Unfortunately it only shows 2 flights, when more flights are available. What am I doing wrong?
Json feed example from endpoint
{
"response": [
{
"flight": {
"number": "6204",
"iata_number": "HV6204",
"icao_number": "TRA6204"
}
},
{
"flight": {
"number": "7012",
"iata_number": "TB7012",
"icao_number": "JAF7012"
}
},
{
"flight": {
"number": "6652",
"iata_number": "HV6652",
"icao_number": "TRA6652"
}
},
{
"flight": {
"number": "1925",
"iata_number": "W61925",
"icao_number": "WZZ1925"
}
},
{
"flight": {
"number": "5075",
"iata_number": "W65075",
"icao_number": "WZZ5075"
}
},
{
"flight": {
"number": "4289",
"iata_number": "W64289",
"icao_number": "WZZ4289"
}
},
{
"flight": {
"number": "7861",
"iata_number": "W67861",
"icao_number": "WZZ7861"
}
},
{
"flight": {
"number": "3066",
"iata_number": "FR3066",
"icao_number": "RYR3066"
}
}
]
} .
The PHP code example
<?php
$url = 'https://api.endpoint'; // path to JSON file
$data = file_get_contents($url);
$flights = json_decode($data, true);
for($i=0; $i<=count($flights['response'][0]['flight']['iata_number']); $i++) {
echo "Flightnumber" . $flights['response'][$i]['flight']["iata_number"] . '<br/>';
}
?>
Any help is very appreciated
What really should be used here is foreach. With foreach you don't have to care about count() of your array:
$url = 'https://api.endpoint'; // path to JSON file
$data = file_get_contents($url);
$flights = json_decode($data, true);
foreach ($flights['response'] as $item) {
echo $item['flight']['iata_number'] . '<br />';
}
Simple demo is here.
If you still want to use for-loop, it should look like:
for ($i = 0; $i < count($flights['response']); $i++) {
echo $flights['response'][$i]['flight']['iata_number'] . '<br />';
}
for($i=0; $i<count($flights['response'][0]['flight']['iata_number']); $i++) {
echo "Flightnumber" . $flights['response'][$i]['flight']["iata_number"] . '<br/>';
}
count($flights['response'][0]['flight']['iata_number']) is always going to equal one, so you're only looping twice as would be expected (two flights). My guess is that's supposed to be count($flights['response']) or something similar.
You can use array_walk_recursive
array_walk_recursive($jarr, function($v, $k) use (&$flights){
if($k == 'iata_number') $flights[] = $v;
});
Live example :- https://3v4l.org/5Rp9K

json-php giving filed out put two times?

There is records about the login_ids in json array. I want to fetch required results in json-php decode function. It is giving the login_id two times on top and bottom for each row. I there any way not to print the login_id in the value filed? The code details are given below.
<?php
$json = '{"records" :
[
{
"Name": "Jhon",
"Age": "45",
"Place": "Kettle",
"Phone": "9834453",
"log_id": "216"
},
{
"Name": "Bill",
"Age": "41",
"Place": "Ottava",
"Phone": "4513453",
"log_id": "215"
},
{
"Name": "James",
"Age": "39",
"Place": "Mexico",
"Phone": "3456734",
"log_id": "217"
},
{
"Name": "larry",
"Age": "51",
"Place": "New city",
"Phone": "34890453",
"log_id": "213"
}
]
}';
$myjson = json_decode($json, true); // decode the json string to an array
foreach ( $myjson['records'] as $row ) { // loop the records
echo 'Details of login id: '. $row['log_id']. '<br/>';
foreach ( $row as $field => $value ) { // loop the fields
echo $field . ': '. $value . '<br>';
}
echo '<br/>';
}
?>
Also is there any simple method to print the required login id (i.e where the login_id="217") so that the address of one person is given out put.
Following code my be better but not tested.
foreach ( $myjson['records'] as $row ) {
if ($row['log_id'] =='216') { // login id to be checked
echo 'Details of login id: '. $row['log_id']. '<br/>';
foreach ( $row as $field => $value ) { // loop the fields
if ($field != "log_id") { // hide the login id t bottom
echo $field . ': ' . $value . '<br>';
}
}
echo '<br/>';
}
}
Test the field name before printing it.
foreach ($row as $field => $value {
if ($field != "log_id") {
echo $field . ': ' . $value . '<br>';
}
}

Invalid argument in foreach

I am using the following to retrieve comments from FB:
$url = urlencode("http://*****.com/pages/view?id=2153&item=Mens-Collection-Shoes");
$request_url ="https://graph.facebook.com/comments/?ids=" . $url;
$requests = file_get_contents($request_url);
when I print_r($requests); I get the following but cannot work out how to format it with a foreach loop:
{
"http:\/\/*****.com\/pages\/view?id=2153&item=Mens-Collection-Shoes": {
"comments": {
"data": [{
"id": "123456",
"from": {
"name": "Laurelle",
"id": "123456"
},
"message": "I love these",
"can_remove": false,
"created_time": "2012-11-20T10:20:16+0000",
"like_count": 0,
"user_likes": false
} {
"id": "123456",
"from": {
"name": "Dan",
"id": "123456"
},
"message": "I know, just stunning!",
"can_remove": false,
"created_time": "2012-11-20T14:24:15+0000",
"like_count": 0,
"user_likes": false
}],
"paging": {
"next": "https:\/\/graph.facebook.com\/*****\/comments?limit=25&offset=25&__after_id=*****"
}
}
}
}
I'm trying to get:
data->from->id
data->from->name
data->message
data->created_time
I've tried:
$fb_response = json_decode($requests);
foreach($fb_response->data as $item){
echo $item->from->id . '<br />';
echo $item->from->name . '<br />';
echo $item->message . '<br />';
echo $item->created_time . '<br /><br />';
}
But no luck
I think you're looking for:
$originalUrl = "http://*****.com/pages/view?id=2153&item=Mens-Collection-Shoes";
$url = urlencode($originalUrl);
...
foreach($fb_response->$originalUrl->comments->data as $item) {
data isn't the name of a property directly inside the JSON document; it's under http://*****.com/pages/view?id=2153&item=Mens-Collection-Shoes and comments.

Parsing JSON array with PHP foreach

Wondering why my PHP code will not display all "Value" of "Values" in the JSON data:
$user = json_decode(file_get_contents($analytics));
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
}
foreach($user->data->values as $values)
{
echo $values->value . "\n";
}
The first foreach works fine, but the second throws an error.
{
"data": [
{
"id": "MY_ID/insights/page_views_login_unique/day",
"name": "page_views_login_unique",
"period": "day",
"values": [
{
"value": 1,
"end_time": "2012-05-01T07:00:00+0000"
},
{
"value": 6,
"end_time": "2012-05-02T07:00:00+0000"
},
{
"value": 5,
"end_time": "2012-05-03T07:00:00+0000"
}, ...
You maybe wanted to do the following:
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
You need to tell it which index in data to use, or double loop through all.
E.g., to get the values in the 4th index in the outside array.:
foreach($user->data[3]->values as $values)
{
echo $values->value . "\n";
}
To go through all:
foreach($user->data as $mydata)
{
foreach($mydata->values as $values) {
echo $values->value . "\n";
}
}
$user->data is an array of objects. Each element in the array has a name and value property (as well as others).
Try putting the 2nd foreach inside the 1st.
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}

Categories