This is json data i received:
{"id":"8","cardnum":"5678887","point_collected":"26","date":"2015-05-06"}
{"id":"15","cardnum":"3435435","point_collected":"20","date":"2015-05-04"}
{"id":"11","cardnum":"5678887","point_collected":"50","date":"2015-05-03"}
{"id":"12","cardnum":"5678887","point_collected":"80","date":"2015-05-02"}
{"id":"14","cardnum":"5678887","point_collected":"10","date":"2015-05-02"}
I want to get the "cardnum" for comparison with my $usercard, and display all the result with the same "cardnum" and encode into json again.
This is my current code:
$decodeTrans=json_decode($transJson, true);
$response = array();
$usercard = "5678887";
foreach ($decodeTrans as $dt)
{
$membercard = $dt['cardnum'];
if ($membercard == $usercard)
{
$response["success"] = 1;
$response ['id'] = $dt['id'];
$response ['card_number'] = $membercard;
$response ['point_collected'] = $dt['point'];
$response ['date'] = $dt['date'];
echo json_encode($response);
}
}
}
}
I get this error: Invalid argument supplied for foreach()
Anyone can help? Thanks in advance.
Your input is not a valid JSON string. However, each line is still a valid JSON string. Update your code to split the $transJson and convert each line to PHP object using json_decode:
$response = array();
$usercard = "5678887";
foreach(explode("\n", $transJson) as $line)
{
$dt = json_decode(trim($line), true);
$membercard = $dt['cardnum'];
if ($membercard == $usercard)
{
$response["success"] = 1;
$response ['id'] = $dt['id'];
$response ['card_number'] = $membercard;
$response ['point_collected'] = $dt['point_collected'];
$response ['date'] = $dt['date'];
echo json_encode($response);
}
}
The demo: http://sandbox.onlinephpfunctions.com/code/3335a3fa9edb5a3b8d7e73fd85d4bad806e5ac92
Related
this is my code :
if ($API->connect("192.168.81.130", "admin", "")) {
$API->write('/ip/route/print', false);
$API->write('=.proplist=.id', false);
$API->write('=.proplist=dst-address', false);
$API->write('=.proplist=pref-src', false);
$API->write('=.proplist=gateway');
$result = $API->read();
$API->disconnect();
foreach ($result as $route){
$response['id'] = $route['.id'];
$response['dst-address'] = $route['dst-address'];
if (isset($route['pref-src'])) {
$response['pref-src'] = $route['pref-src'];
} else {
$response['pref-src'] = "";
}
$response['gateway'] = $route['gateway'];
$array[] = $response;
echo json_encode($array);
}
}
and the output is :
[{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"}][{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"},{"id":"*420639B3","dst-address":"192.168.81.0\/24","pref-src":"192.168.81.130","gateway":"ether1"}]
result for "[{"id":"*2","dst-address":"0.0.0.0/0","pref-src":"","gateway":"192.168.1.1"}]" is show twice.
i want the out put like this :
> [{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"},{"id":"*420639B3","dst-address":"192.168.81.0\/24","pref-src":"192.168.81.130","gateway":"ether1"}].
can anyone help me?.
You need to initialize your array each time round the loop otherwise you are just adding to it each time, hence the duplication
You also need to move the echo of the json string to outside the loop
foreach ($result as $route){
$response = array();
$response['id'] = $route['.id'];
$response['dst-address'] = $route['dst-address'];
if (isset($route['pref-src'])) {
$response['pref-src'] = $route['pref-src'];
} else {
$response['pref-src'] = "";
}
$response['gateway'] = $route['gateway'];
$array[] = $response;
}
echo json_encode($array);
I've got this data: http://api.tvmaze.com/shows?page=0
What i am trying to achieve is looping over the data and echo each id. This is the code i used:
<?php
$url = ('http://api.tvmaze.com/shows?page=0');
$json = file_get_contents($url);
$response = json_decode($json, TRUE);
foreach( $response as $serie){
foreach( $serie as $info => $value){
echo $info->$value["id"];
}
}
I don't really know what i am doing wrong.. Do you guys have any idea?
Greetz,
Try below code for getting id and url. You have to use array because you are passing TRUE in json_decode().
<?php
$url = ('http://api.tvmaze.com/shows?page=0');
$json = file_get_contents($url);
$response = json_decode($json, TRUE);
foreach( $response as $serie)
{
echo $serie['id']."->".$serie['url']."<br>";
}
?>
Keep it simple to fetch ids you wanted,
$url = ('http://api.tvmaze.com/shows?page=0');
$json = file_get_contents($url);
$response = json_decode($json, TRUE);
echo "<pre>";
foreach ($response as $value) {
echo $value['id']."<br/>"; // you will get ids in here only
}
i have this JSON
{
"count":"3",
"num":"1",
"array":[
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":0
},
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":1
}
]
}
created it in android and send it by **HttpPost**
, i've tried a lot of ways to get the data in the php, my php file is this:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn,true);
$count = $json_data->{'count'};
$num = $json_data["num"];
$response["data"]=$count;
$response["data2"]=$num;
// echoing JSON response
echo json_encode($response);
?>
but $count and $num always returns null, any help please, and thanks.
$json_data = json_decode($josn,true);
this returns an array, not an object (which you are using later in the code). Use this to convert the json string to an object:
$json_data = json_decode($josn);
Or you could just use arrays, in which case your code should look like:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn, true); // using true to get array
$count = $json_data["count"]; // accessing array values as normal
$num = $json_data["num"]; // accessing array values as normal
$response["data"] = $count; // instead of setting $count first you could just add
$response["data2"] = $num; // the json_data array values directly to the response array
// echoing JSON response
echo json_encode($response);
I am attempting to fetch JSON from Instagram according to a number of URL parameters, the JSON is then decoded and then the objects required are then encoded into my own JSON format. Whilst I know this sound a little ridiculous, it is what is required. My only issue here is that for some reason it does not encode each section of JSON, it will only work for one item. The code is as below.
<?php
function instagram($count=16){
$igtoken = $_GET['igtoken'];
$hashtag = $_GET['hashtag'];
$url = 'https://api.instagram.com/v1/tags/'.$hashtag.'/media/recent/?access_token='.$igtoken.'&count='.$count;
$jsonData = json_decode((file_get_contents($url)));
$jsonData = json_decode((file_get_contents($url)));
foreach ($jsonData->data as $key=>$value) {
$response = array();
$response["data"] = array();
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
$result = json_encode($response);
}
return $result;
}
echo instagram();
?>
It will work for each section of JSON if I do something like this instead:
$result .= '<li>
'.$value->caption->from->username.'<br/>
'.$value->caption->from->profile_picture.'<br/>
'.$value->caption->text.'<br/>
'.$value->images->standard_resolution->url.'<br/>
'.$value->caption->created_time.'<br/>
</li>';
I feel I have bodged up somewhere with the array, however i'm not entirely sure.
What if we move $response["data"] and $result varia out of foreach?
Have you tried this?
$response = array();
$response["data"] = array();
foreach ($jsonData->data as $key=>$value) {
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
}
$result = json_encode($response);
return $result;
I am getting a json format like this
[{"service":{"title":"karthik","city":"chennai"}},{"service":{"title":"siva","city":"madurai"}}]
from code
$rt = array();
$rt["service"]["title"] = karthik;
$rt["service"]["city"] = chennai;
$t = array();
$t["service"]["title"] = siva;
$t["service"]["city"] = madurai;
echo json_encode(array($rt,$t));
but i need the same format of json result from this code
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id
FROM task");
while($row=mysql_fetch_array($a))
{
$jsonrow=new stdClass;
$jsonrow->title=$row['title'];
$jsonrow->city=$row['city'];
$jsonresponse=new stdClass;
$jsonresponse->service=$jsonrow;
}
echo json_encode(array($jsonresponse));
but the result actually i get from the above code is
[{"service":{"title":"Event Help","city":"Santa Fe"}}]
please someone help me on this issue.....
Use an array store all the values returned from the query
$array = array();
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id
FROM task");
while($row=mysql_fetch_array($a))
{
$jsonrow=new stdClass;
$jsonrow->title=$row['title'];
$jsonrow->city=$row['city'];
$jsonresponse=new stdClass;
$jsonresponse->service=$jsonrow;
$array[] = $jsonresponse;
}
echo json_encode(array($array));
you are overwriting $jsonresponse in your while loop, you should add this into array and json_encode this array
$response = array();
while( ... ){
...
$response[] = $jsonresponse;
}
echo json_encode($response);
try like this
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id FROM
task");
$jsonrow=new stdClass;
$jsonresponse=new stdClass;
while($row=mysql_fetch_array($a)) {
$jsonrow->title=$row['title']; $jsonrow->city=$row['city'];
$jsonresponse->service=$jsonrow;
}