Print each element of json curl execution - php

I have a curl function to call a service that return output like this
[{"idpacket":1,"packetname":"Silver","packetdesc":"Silver is da best","packetprize":"Rp 20000","packettime":"365 days"}]
I wanna echo all of element into table row
How i do that? I always get error on foreach function. Please help
This is my code:
<?php
//step1
$cSession = curl_init();
//step2
curl_setopt($cSession,CURLOPT_URL,"http://localhost:8080/packet");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
//step3
$result=curl_exec($cSession);
//step4
curl_close($cSession);
//
foreach ((array) $result as $item) {
print_r($item['idpacket']);
}
?>
Thank you :)

I got this conclusion as I understood
write this code and check :
print_r((array)$result);
its place your JSON into an array does not decode your JSON like this:
Array
(
[0] => [{"idpacket":1,"packetname":"Silver","packetdesc":"Silver is da best","packetprize":"Rp 20000","packettime":"365 days"}]
)
if you want to access 'idpacket'
write like this:
$result_array = json_decode($result,true);
foreach ((array) $result_array as $item) {
print_r($item['idpacket']);
}

You could write something like
<?php
$resultArr = json_decode($result,true);
$header="<tr>";
$row="<tr>";
echo "<table>";
foreach($resultArr[0] as $col => $val)
{
$header.="<td>".$col."</td>";
$row.="<td>".$val."</td>";
}
$header.="</tr>";
$row.="</tr>";
echo $header;
echo $row;
echo "</table>";
?>

Related

How to iterate over an item of objects and array

I do not know how to iterate on this output, it can be simple but try several methods without success.
I have the result of a query that throws a json with objects and fixes, but I can not get the cpu, memory and disk values:
<?php
// How to read influx data with curl
$query = urlencode("select * from calls limit 1");
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 1); //timeout in seconds
curl_setopt($ch, CURLOPT_URL,"http://127.0.0.1:8086/query?db=myDB&q=$query");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$res = json_decode(curl_exec ($ch));
curl_close ($ch);
var_dump($res);
?>
and I get this output:
{"results":[{"statement_id":0,"series":[{"name":"custom","tags":{"hostname":"LINUX01"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",1,78,0,0]]},{"name":"custom","tags":{"hostname":"LINUX02"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",6,48,0,0]]},{"name":"custom","tags":{"hostname":"LINUX03"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",5,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX04"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",35,94,0,0]]},{"name":"custom","tags":{"hostname":"LINUX05"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",3,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX06"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",57,25,0,0]]},{"name":"custom","tags":{"hostname":"LINUX07"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",40,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX08"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",41,30,0,0]]},{"name":"custom","tags":{"hostname":"ues90078"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",40,20,0,0]]},{"name":"custom","tags":{"hostname":"LINUX09"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",33,45,0,0]]},{"name":"custom","tags":{"hostname":"LINUX041"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",31,30,0,0]]},{"name":"custom","tags":{"hostname":"LINUX042"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",33,8,0,0]]},{"name":"custom","tags":{"hostname":"LINUX043"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",54,10,0,0]]}]}]}
Try for example:
foreach ($res as $test) {
echo $test->statement_id->cpu;
}
I wish I could get this:
hostname time cpu mem load load
linux01 1970-01-01T00:00:00Z 1 78 0 0
Sorry for my bad English.
You will have a difficult time working with this data as is, because most of the data is unkeyed, and that makes it misleading to work with as an object. It would be easier in this case if you worked with the array. You can do this by using true as the second parameter of the decode.
$data = json_decode(curl_exec ($ch), true);
$results = $data['results'];
foreach ($results['series'] as $server) {
$cpuIndex = array_search('cpu', $server['columns']);
echo $server['values'][$cpuIndex];
}
You need to convert it to from JSON to an Object or Array.
Here's a common Array situation:
$results = json_decode('{"results":[{"statement_id":0,"series":[{"name":"custom","tags":{"hostname":"LINUX01"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",1,78,0,0]]},{"name":"custom","tags":{"hostname":"LINUX02"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",6,48,0,0]]},{"name":"custom","tags":{"hostname":"LINUX03"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",5,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX04"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",35,94,0,0]]},{"name":"custom","tags":{"hostname":"LINUX05"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",3,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX06"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",57,25,0,0]]},{"name":"custom","tags":{"hostname":"LINUX07"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",40,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX08"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",41,30,0,0]]},{"name":"custom","tags":{"hostname":"ues90078"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",40,20,0,0]]},{"name":"custom","tags":{"hostname":"LINUX09"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",33,45,0,0]]},{"name":"custom","tags":{"hostname":"LINUX041"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",31,30,0,0]]},{"name":"custom","tags":{"hostname":"LINUX042"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",33,8,0,0]]},{"name":"custom","tags":{"hostname":"LINUX043"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",54,10,0,0]]}]}]}', true);
foreach ($results["results"][0]["series"] as $array) {
echo "<table>";
echo "<thead>";
echo "<tr>";
foreach ($array["columns"] as $value) {
echo "<th>{$value}</th>";
}
echo "</tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
foreach ($array["values"][0] as $value) {
echo "<td>{$value}</td>";
}
echo "</tr>";
echo "</tbody>";
echo "<table>";
}
If you want something specific:
foreach ($results["results"][0]["series"] as $array) {
foreach ($array["columns"] as $key => $value) {
if ($value === "cpu") $column = $key;
}
echo "cpu: {$array["values"][0][$column]}.<br>";
}
To add hostname, simple add:
echo "<tr>";
echo "<th colspan=" . count($array["columns"]) . ">{$array["tags"]["hostname"]}</th>";
echo "</tr>";
after echo "<thead>";.

Read and print json array in php

I have a JSON array like below. I want to print only the values of the name. But I am getting undefined index name and getting value of name.below is my json.
[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]
my code
foreach($doc_array as $data => $mydata)
{
foreach($mydata as $key=>$val)
{
echo $val['name'];
}
}
How to get the values of name from docProfile? Any help would be greatly appreciated
Inside your foreach you don't need to loop again since docProfile is an index of the json object array
Just simple access it
echo $mydata['docProfile']['name'].'<br>';
so your foreach would be like this
foreach($doc_array as $data => $mydata) {
echo $mydata['docProfile']['name'].'<br>';
}
Demo
Try to something Like this.
<?php
$string = '[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$arr = json_decode($string, true);
echo $arr[0]['docProfile']['name'];
?>
This array just have one row but if your array have more row you can use it;
you need to decode JSON at first.
$doc_array =json_decode($doc_array ,true);
foreach($doc_array as $key=> $val){
$val['docProfile']['name']
}
<?php
$json_str='[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$json_arr = (array)json_decode($json_str,true);
foreach($json_arr as $iarr => $ia)
{
foreach($ia["docProfile"] as $doc => $docDetails)
{
if($doc =="name")
{
echo $ia["docProfile"]["name"];
}
}
}
?>
This code gives you the answer

How to create valid array from JSON to use it at foreach loop

I have this text ($results):
{"data":{"summary":{"records":67,"page":1,"total":67,"hasMore":0},"reservations":[{"id":1111111,"property":"villadianna","from":"2016-07-18","to":"2016-07-25"},"pricing":{"price":1164.2400,"currency":"EUR","retail":1323},"clientInfo":{"firstName":"pera","lastName":"peric","email":"myemail#gmail.com"},"status":1,"offline":0},{"id":222222,"property":"villadianna", etc. ... ...
Now I need to get reserations array and make foreach loop so I try:
...
$result = curl_exec($ch);
curl_close($ch);
$json = json_decode($result);
foreach ($json->reservations as $element) {
print_r($element);
}
but I get errors:
How to create html table with foreach loop only for reservations ?
...
$result = curl_exec($ch);
curl_close($ch);
$json = json_decode($result);
foreach ($json->data->reservations as $element) {
print_r($element);
}

How to go through each element in JSON array in PHP

I want to echo out each element of an object of a JSON array like this:
{"request_list":[{"id":"1","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null},{"id":"3","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null}]}
But i cannot do it.I tried somethinglikethis:
$object = json_decode($json, true);
$request_list = $object->request_list;
foreach($request_list as $r){
echo $r->name;
echo $r->blood_type;
echo $r->phone_number;
}
But I got an error like:
Invalid argument supplied for foreach()
As you have mark return as array true in json_decode. So, try below code.
$object = json_decode($json, true);
$request_list = $object['request_list'];
foreach($request_list as $r){
echo $r['name'];
echo $r['blood_type'];
echo $r['phone_number'];
}
Use this
$object = json_decode($json, true);
$request_list = $object['request_list'];
foreach($request_list as $r){
echo $r['name'];
echo $r['blood_type'];
echo $r['phone_number'];
}
try
$json = '{"request_list":[{"id":"1","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null},{"id":"3","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null}]}';
$data = json_decode($json );
$request = $data->request_list;
foreach($request as $request_data){
echo $request_data->id;
echo $request_data->name;
echo $request_data->surname;
}

cURL and json data convert into array and get only temp data

I am new using json data. I am trying to call an api using cURL and converting it into array. I just want the temp data using foreach loop. But i am getting Invalid argument supplied for foreach() error. My code
$cSession = curl_init();
curl_setopt($cSession,CURLOPT_URL,"http://api.openweathermap.org/data/2.5/forecast/daily?q=dhaka%2Cbangladesh&mode=json&units=metric&cnt=3");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result = curl_exec($cSession);
curl_close($cSession);
//echo $result;
//$i = 3 as i am requesting 3 day data
for ($i=0; $i <3 ; $i++) {
foreach ($result as $value) {
echo $value['temp'][0]['day'];
echo $value['temp'][0]['min'];
echo $value['temp'][0]['max'];
echo $value['temp'][0]['night'];
echo $value['temp'][0]['eve'];
echo $value['temp'][0]['morn'];
}
}
This should work for you:
$json = json_decode($result);
$res = $json->{'list'};
foreach ($res as $value) {
echo $value->{'temp'}->{'day'} . "<br>";
echo $value->{'temp'}->{'min'} . "<br>";
echo $value->{'temp'}->{'max'} . "<br>";
echo $value->{'temp'}->{'night'} . "<br>";
echo $value->{'temp'}->{'eve'} . "<br>";
echo $value->{'temp'}->{'morn'} . "<br>";
}
In your query string you have the value metric&cnt=3 this is what you want for days to be extracted if you get from cnt=10 you will have 10 results. No need for a for loop.
With the curl_exec you'll get a json as a string, you have to parse it first to use it.
Try this: http://php.net/manual/en/function.json-decode.php
And don't forget to set the second parameter to true if you want the result as an array.
the result is JSON that you should parse with json_decode first
edit with more code:
...
$result = json_decode($result,true);
for ($i=0; $i <3 ; $i++) {
foreach ($result['list'] as $value) {
echo $value['temp']['day'];
echo $value['temp']['min'];
...
curl_exec with the option CURLOPT_RETURNTRANSFER set to true will return the result of fetch the url you have set so your variable $result is a STRING.
You hace to convert to an array:
$cSession = curl_init();
curl_setopt($cSession,CURLOPT_URL,"http://api.openweathermap.org/data/2.5/forecast/daily?q=dhaka%2Cbangladesh&mode=json&units=metric&cnt=3");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result = curl_exec($cSession);
curl_close($cSession);
$result = json_decode($result,true);
//echo $result;
//$i = 3 as i am requesting 3 day data
for ($i=0; $i <3 ; $i++) {
foreach ($result as $value) {
echo $value['temp'][0]['day'];
echo $value['temp'][0]['min'];
echo $value['temp'][0]['max'];
echo $value['temp'][0]['night'];
echo $value['temp'][0]['eve'];
echo $value['temp'][0]['morn'];
}
}

Categories