Outputting manual JSON in PHP - php

I am building some JSON myself like so:
echo '{ "type": "root",';
echo '"children" : [';
echo '{';
echo '"identifier": "Contractor",';
echo '"title": "Contractor",';
echo '"autoIdentifier": true,';
echo '"options": [';
foreach ($names as $n){
echo '{';
echo '"text": '.'"'.$n['name'].'",';
echo '"identifier": '.'"'.$n['id'].'"';
echo '},';
}
echo '],';
echo '"title": "TEST",';
echo '"description": ""';
echo '}';
As you can see i am looping through some data to print into the JSON output. The problem i am having is the last echo within the loop. This is because it currently has a comma after the bracket.
However if it is the last element within my data loop, i want the comma to be removed so that it creates proper JSON.
How can i achieve this? With some kind of counter and then an if statement?

$names = array_map(function($name) {
return '{ "text":"' . $name['name'] . '", "identifier":"' . $name['id'] . '" }';
}, $names);
echo '{ "type": "root",';
echo '"children" : [';
echo '{';
echo '"identifier": "Contractor",';
echo '"title": "Contractor",';
echo '"autoIdentifier": true,';
echo '"options": [';
echo implode(',', $names);
echo '],';
echo '"title": "TEST",';
echo '"description": ""';
echo '}';

I'd seriously prefer just using PHPs JSON encoding features, json_encode. For example, what if the $n["name"] had a quote in it? Your JSON would be invalid, but if you used json_encode, it'd take care of that.
$child = [
"identifier" => "Contractor",
"autoIdentifier" => true,
"options" => [],
"title" => "TEST",
"description" => ""
];
foreach ($names as $n)
{
$child["options"][] = [
"text" => $n["name"],
"identifier" => $n["id"]
];
}
header( "Content-Type: application/json" );
echo json_encode( ["type" => "root", "children" => [$child]] );

change your loop to:
$var = '';
foreach ($names as $n){
$var .= '{';
$var .= '"text": "'.$n['name'].'",';
$var .= '"identifier": "'.$n['id'].'"';
$var .= '} ,';
}
$var = rtrim($var,",");
echo $var;
OR
change your code like this:
$var = '{ "type": "root","children" : [{"identifier": "Contractor","title": "Contractor","autoIdentifier": true,"options": [';
foreach ($names as $n){
$var .= '{"text": "'.$n["name"].'","identifier": "'.$n["id"].'"} ,';
}
$var = rtrim($var,",");
$var = '],"title": "TEST","description": ""}';
echo $var;

Related

Get Parent Value and Combine To Child Value Using Loop

i have data and want to modify the result using parent and child method. As an example below.
I try with following code but have no luck because the last iteration give wrong result as seen on screenshot below, Is there any idea how to solve it?? live code here https://paiza.io/projects/vS4BHo0mMrKiJZoPpMoNvQ
<?php
$data = array("022.04.GA", "4660", "4660.CBD", "4660.CBD.002", "52", "A", "533111", "022.04.WA", "4631", "4631.EAF", "4631.EAF.001", "51", "B", "524111", "524113", "52", "C", "521211", "524113", "4631.EAH", "4631.EAH.001", "51", "B", "521211", "522131", "4634", "4634.EAG", "4634.EAG.001", "51", "C", "521219", "522191");
echo "<table>";
echo "<tr>";
echo "<td>Code</td><td>Result</td>";
foreach($data as $item)
{
$length = strlen($item);
$data = '';
if($length==9) {
$value = $item;
} elseif($length==4) {
$value .= $data.'.'.$item;
} elseif($length==8) {
$output = substr($item,-4);
$value .= $data.$output;
} elseif($length==12) {
$output = substr($item,-4);
$value .= $data.$output;
} elseif($length==3) {
$value .= $data.'.'.$item;
} elseif($length==1 or $length==2) {
$value .= $data.'.'.$item;
} else {
$value .= $data.'.'.$item;
}
echo "<tr>";
echo "<td>$item</td>";
echo "<td>$value</td>";
echo "</tr>";
}
echo "</tr>";
echo "</table>";
?>

convert json data from array to object and print out as table [duplicate]

This question already has answers here:
How can I parse JSON into a html table using PHP?
(5 answers)
Closed 6 years ago.
Guys any help is appreciated. New to php & learning as I go.
My Objective: change the array to an object and print it out as a table.
Below is my json data which is save as people.txt file.
{
"people": [
{
"first_name": "John",
"last_name": "Smith",
"city": "NY",
"state": "New York"
},
{
"first_name": "Jane",
"last_name": "Smith",
"city": "Paris",
"state": "France"
},
{
"first_name": "John",
"last_name": "Smith",
"city": "Orlando",
"state": "Florida"
},
{
"first_name": "Jane",
"last_name": "Smith",
"city": "Toronto",
"state": "Canada",
}
]
}
//this issue is when I try to change the from array to an object using $people_data = json_decode ($json_data); without the second parameter "true". or even using $people_data = json_decode (json_encode ($json_data));
//HERE IS MY PHP CODE
$json_data = file_get_contents ("people.txt");
// I was able to use $people_data = json_decode ($json_data, true); to output my table just fine by changing my data to an array.
$people_data = json_decode ($json_data, true);
$output = "<table border='1' style=' border-collapse:collapse; 'width=25%'>";
$output .= "<tr>";
$output .= "<th>". "First Name" ."</th>";
$output .= "<th>". "Last Name" ."</th>";
$output .= "<th>". "City" ."</th>";
$output .= "<th>". "State" ."</th>";
$output .= "</tr>";
foreach ($people_data ["people"] as $person) {
$output .= "<tr>";
$output .= "<td>". $person ["first_name"] ."</td>";
$output .= "<td>". $person ["last_name"] ."</td>";
$output .= "<td>". $person ["city"] ."</td>";
$output .= "<td>". $person ["state"] ."</td>";
$output .= "</tr>";
}
$output .= "</table>";
echo $output;
?>
this is a pic of my results using an "array", trying to get the same result as "object".
json table
in your loop, just set it as an array.
It is especially useful to dynamically set, unset or modify object properties,it s made for, especially in classes to avoid volatile destruction. Easier to deal with too than objects, also faster as , converted as an array, it uses indexes (kinda like in mysql):
$list = ["first_name", "last_name", "city", "state"]; // set outside loop
$type = "people";
foreach ($people_data [$type] as $key => $person) {
$person = (array) $person; // convert to array
unset($people_data[$type][$key]); // purge unnecessary ram
$output .= '<tr id="' . $type . 'Id_' . $key . '">'; // use single quotes for perf gain
foreach ($list as $key2 => $val) {
$output .= '<td class="' . $val . '">' . $person [$val] . '</td>';
}
$output .= '</tr>';
}
Bonus:
You are on the right track to use string concat (.=). and only echo once. This is 10 times faster. multiple echo in a script is a perf killer.
In the same manner, use simple quotes for your concat and not double quotes so that PHP does not have to check for variables inside it.
All in all, for small stuff or low traffic this does not change anything but when it comes to heavier loads, you double the perfs of your scripts.

foreach loop for display data in elements, for json whit multiple array

I have a json from an external domain, I need to create a list of posts, and I have to write the data taken from json in elements
{
"dati": [
{
"id": 98762,
"tipo": "eventi",
"titolo": “TITOLO 1“,
"sottotitolo": "",
"img": "http://www.asdsad.it",
"url": "http://www.asdsad.it",
"data_da": "2016-01-05",
"data_a": "2016-01-05",
"stato": "IT",
"regione": "IT.10",
"provincia": "IT.10.FM",
"citta": "Porto Sant\'Elpidio",
"indirizzo": "Via Faleria, 15"
},
{
"id": 97004,
"tipo": "corsi",
"titolo": “TITOLO 2”,
"sottotitolo": "",
"img": “http://www.asdsad.it”,
"url": "http://www.asdsad.it",
"data_da": "2016-01-05",
"data_a": "2016-01-05",
"stato": "IT",
"regione": "IT.08",
"provincia": "IT.08.SV",
"citta": "Savona",
"indirizzo": ""
}
]
}
the result will be somenthing like that:
<div id="98762">
<h1>TITOLO 1</h1>
<img src="http://www.asdsad.it" />
<h3>eventi<h3/>
......
</div>
<div id="97004">
<h1>TITOLO 2</h1>
<h3>corsi<h3/>
<img src="http://www.asdsad.it" />
......
</div>
I have try whit this but i get a blank page..
<?php
$data = file_get_contents("url_json");
$dataArray = json_decode($data, true);
foreach ($dataArray as $row){
foreach ($row as $key => $value){
switch ($key) {
case 'id':
echo "<div> $value </div>";
break;
case 'sottotitolo':
echo "<h3> $value </h3>";
break;
case 'img':
echo "<img src=$value >";
break;
// ...
}
}
}
?>
i thing you have an error in json file.Try to fix that one first.After that if you are getting " $dataArray" properly you can use this
$data = file_get_contents("url_json");
$dataArray = json_decode($data, true);
$append_str = '';
foreach ($dataArray['dati'] as $row) {
$append_str .= '<div id="' . $row['id'] . '">'
. '<h1>' . $row['sottotitolo'] . '</h1>'
. '<img src="' . $row['img'] . '" />'
. '</div> ';
}
echo $append_str;
You need to remove “ and ” than you will get the result in jsqon_decode();
You can try this (Example is just for specific issue):
$data = file_get_contents("url_json");
$data = str_replace('“', '"', $data); // replace “ with "
$data = str_replace('”', '"', $data); // replace ” with "
$dataArray = json_decode($data, true);

PHP get json data with json_decode

I'm new to PHP and try to echo out some data from json, but I got stucked in this.
It shows non of the data, but the data is there. The var_dump() shows it to me.
Probably I don't use the array correctly, but I can't find what's wrong. I've this code,
I request some data which I gathered with knockout.js
Knockout gives me a json (as show below)
$json = $_REQUEST[seats];
echo 'requested data raw '. "<br>".$json;
$data = json_decode($json, true);
echo "<br>".'var_dump '. "<br>";
var_dump($data);
foreach ($data as $optie ) {
echo "name = " . $optie->name . "<br>";
echo "optie = " . $optie->optieName . "<br>";
echo "prijs = " . $optie->prijs . "<br>";
}
This is my JSON:
[
{
"name": "Naam 1",
"optie": {
"optieName": "Make_up",
"prijs": 9.95
},
"PrijsFormated": "Euro: 9.95"
},
{
"name": "Naam 2",
"optie": {
"optieName": "Handverzorging",
"prijs": 12.95
},
"PrijsFormated": "Euro: 12.95"
}
]
You should use such loop:
foreach ($data as $optie ) {
echo "name = " . $optie['name'] . "<br>";
echo "optie = " . $optie['optie']['optieName'] . "<br>";
echo "prijs = " . $optie['optie']['prijs']. "<br>";
}
Because using json_decode() with second parameter as true you have created associative array - documentation.
If you would like to access data as object, you should use:
$data = json_decode($json);
instead of
$data = json_decode($json, true);
and then you should use the following loop:
foreach ($data as $optie ) {
echo "name = " . $optie->name . "<br>";
echo "optie = " . $optie->optie->optieName . "<br>";
echo "prijs = " . $optie->optie->prijs. "<br>";
}

Parsing pinterest JSON api with PHP

Hi im having problem parsing this pinterest JSON file, any ideas? thanks
$json = file_get_contents('http://pinterestapi.co.uk/jwmoz/boards');
$obj = json_decode($json);
foreach($obj->body as $item){
$example = $item[0]->name;
echo $example;
}
{
"body":[
{"name":"JMOZ",
"href":"http:\/\/pinterest.com\/jwmoz\/jmoz\/",
"num_of_pins":17,"cover_src":"http:\/\/media-cache-ec4.pinterest.com\/upload\/82190761920643849_2DcDfCUK_222.jpg",
"thumbs_src":
["http:\/\/media-cache-ec5.pinterest.com\/upload\/82190761920643841_dZfvCWmE_t.jpg",
"http:\/\/media-cache-ec4.pinterest.com\/upload\/82190761920194573_aPAbDtHD_t.jpg",
"http:\/\/media-cache-ec2.pinterest.com\/upload\/82190761920194563_dQcOIHvQ_t.jpg",
"http:\/\/media-cache0.pinterest.com\/upload\/82190761920194557_VSSI2uQB_t.jpg"
]
},
{"name":"JMOZ",
"href":"http:\/\/pinterest.com\/jwmoz\/jmoz\/",
"num_of_pins":17,"cover_src":"http:\/\/media-cache-ec4.pinterest.com\/upload\/82190761920643849_2DcDfCUK_222.jpg",
"thumbs_src":
["http:\/\/media-cache-ec5.pinterest.com\/upload\/82190761920643841_dZfvCWmE_t.jpg",
"http:\/\/media-cache-ec4.pinterest.com\/upload\/82190761920194573_aPAbDtHD_t.jpg",
"http:\/\/media-cache-ec2.pinterest.com\/upload\/82190761920194563_dQcOIHvQ_t.jpg",
"http:\/\/media-cache0.pinterest.com\/upload\/82190761920194557_VSSI2uQB_t.jpg"
]
},
{"name":"JMOZ",
"href":"http:\/\/pinterest.com\/jwmoz\/jmoz\/",
"num_of_pins":17,"cover_src":"http:\/\/media-cache-ec4.pinterest.com\/upload\/82190761920643849_2DcDfCUK_222.jpg",
"thumbs_src":
["http:\/\/media-cache-ec5.pinterest.com\/upload\/82190761920643841_dZfvCWmE_t.jpg",
"http:\/\/media-cache-ec4.pinterest.com\/upload\/82190761920194573_aPAbDtHD_t.jpg",
"http:\/\/media-cache-ec2.pinterest.com\/upload\/82190761920194563_dQcOIHvQ_t.jpg",
"http:\/\/media-cache0.pinterest.com\/upload\/82190761920194557_VSSI2uQB_t.jpg"
]
},
{"name":"test I\u00f1t\u00ebrn\u00e2ti\u00f4n\u00e0liz\u00e6ti\u00f8n",
"href":"http:\/\/pinterest.com\/jwmoz\/test-internationaliztin\/",
"num_of_pins":0,
"cover_src":false,
"thumbs_src":false
}],
"meta":{"count":11}
}
It seems the problem is in your usage of the [0] index on $item
$example = $item[0]->name;
This should just be
$example = $item->name;
To access the thumbnails, try
$obj = json_decode($json);
foreach($obj->body as $item){
echo '<li>' . $item->name . '<ul>';
if(!empty($item->thumbs_src))
{
foreach($item->thumbs_src as $thumbs_src){
echo '<li>' . $thumbs_src . '</li>';
}
}
echo '</ul></li>';
}

Categories