Decode Json Object Php - php

My json data looks like this :
{
"amount":550,
"items":[
{"item_id":12334, "price": 504},
{"item_id":12335, "price":206}
]
}
I want to know how to parse this data in order to fetch each information in separate variable.

In PHP you can use json_decode($myJsonString), while in Android you might look for a third party library, GSON is a good one though
$data = json_decode($json);
foreach($data->items as $item) {
echo $item->item_id . ' ' . $item->price;
}

In PHP use json_decode
In Java use org.json.simple

Create local variable suppose $response;
store your output in $response;
You can fetch price by following code.
foreach ($response->items as $item){
echo $item->price;
echo "<br>";
}

Related

Parsing part of a json object with multi levels using PHP

If you open the URL, you'll see that it's a very long string of sub objects. I want to extract the values for the 70 position. So far I've been able to extract the first tree without a problem ... But if you go deeper then I don’t get any feedback at all. Please check the code below and tell me, what am I doing wrong?
$url= "https://bwt.cbp.gov/api/waittimes";
$port = file_get_contents($url); // put the contents of the file into a variable
$data = json_decode($port); // decode the JSON feed
echo $data[69]->port_name.'<br>';
echo $data[69]->port_status.'<br>';
echo $data[69]->passenger_vehicle_lanes->maximum_lanes.'<br>';
echo $data[69]->passenger_vehicle_lanes->standard_lanes->lanes_open.'<br>';
The following is working for me:
$url= "https://bwt.cbp.gov/api/waittimes";
$port = file_get_contents($url); // put the contents of the file into a variable
$data = json_decode($port, true); // decode the JSON feed
echo "There are ".count($data)."Ports".PHP_EOL;
$found=false;
foreach ($data as $key => $value) {
//EDIT AFTER COMMENT**
if($value['port_number']==250401){
echo $value['port_name'].' '.$value['crossing_name'].PHP_EOL;
$found=true;
break;
}
}
if(!$found) echo "couldn't find port #";
can you try to change json_decode($port, true); (true will change object to array and it will be better to access it) like this and access it like in array echo $data[69]['passenger_vehicle_lanes']['maximum_lanes'].'<br>';

Save a array to MySQL

I got this API Moves PHP Script up and running, but i can't seem to figure out how to save the array to a MySQL db? How do i do that? I want to save the information, but also print the information on the page like i do now?
I use the script from this git .. https://github.com/borivojevic/moves-api-php
$Moves = new \Moves\Moves($access_token);
$data = $Moves->dailySummary(array('pastDays' => 1));
foreach($data as $dag)
{
echo 'Dato: <b>', $dag['date'], '</b> <br />';
foreach($dag['summary'] as $aktivitet)
{
if($aktivitet['activity'] == 'walking')
{
$daglig_procent = ($aktivitet['steps']/10000 * 100);
echo 'Antal skridt: <i>', $aktivitet['steps'], '</i>';
echo '<br />';
echo 'Procent: <i>', round($daglig_procent), ' % </i>';
}
}
echo '<hr />';
}
}
If you want to save an array to a db, json_encode it and save the json string in a text/varchar field; json_decode it to get the array back from the db data.
You can use these function
serialize
or
json_encode
This this an example:
$mydata=Array("some"=>Array("fhdlslfd"=>"gklhml", "giuolmmlh"), "gfukilfkgl");
You can simply use serialize($mydata); for add in bdd and unserialize($resultatsql); for use the vars from bdd

Object of std:: class cannot be converted to string

Below is a sample json code that I want to access...This json is actually coming from an API. Whenever I copy and paste the entire json in json lint..It says valid json..
foreach ($movies as $movie) {
echo "theaters ".var_dump($movie->release_dates->theater)";
}
//Im actually trying to access a nested json in php... Something like
{
"movies":[{
"tile":"Cowboys";
"release_dates":{"theater":"2013-11-29"},
so on....
Whenever I try to write the above it gives me an error Object of stdclass cannot be converted to string ....Or if I write
$x = json_decode(var_dump($movie->release_dates->theater), true)";
echo "theaters "$x[0];
It gives an output like string[10]:2013-11-25 string[10]:2013-11-30....So on..What is the error....
$data = json_decode($movies, true);
foreach ($data as $movie) {
echo "theaters ".implode(', ', $movie->release_dates->theater)";
}

JavaScript & JSON

I am new to JS & JSON.I am struggle with converting JSON array to JavaScript array.How to do that? Here is my code:
var data = {
items: [
<? $i=1; foreach($query->result() as $row){ ?>
<? if($i!=1){ ?>,<? } ?>
{label: '<?=$row->district_name;?>', data: <?=$row->countid;?>}
<? $i++; } ?>
]
};
how to get the JSON array value to JavaScript Array.
i just tried but it doesn't work. please some suggestions.
here is my javascript array
for(i=0;i<5;i++){
chartData[i]=data.items[i].label+";"+data.items[i].data;
}
As the others already said, be careful when talking about JavaScript and JSON. You actually want to create a JavaScript object and not JSON.
Don't mix PHP and JavaScript like this. It is horrible to maintain. Create an array beforehand, encode it as JSON* and print it:
<?php
$results = $query->result(); // get results
function m($v) { // a helper function for `array_map`
return array('label' => $v->district_name,
'data' => $v->countid);
}
$data = array('items' => array_map('m', $results));
?>
var data = <?php echo json_encode($data); ?>
*: Here we use the fact that a JSON string is valid JavaScript too. You can just echo it directly in the JavaScript source code. When the JS code runs, it is not JSON, it is interpreted as JavaScript object.
You really oughtn't think too hard about this. PHP does a fine job of serializing arrays as JSON.
var data = {
items: <?php
$arr = array();
foreach($query->result() as $row) {
$arr[] = array('label' => $row->district_name,
'data' => $row->countid);
}
echo json_encode($arr);
?>
};
[insert same disclaimer as above about how you're really trying to create a JavaScript object]
This is JSON:
var foo = "{bar: 1}";
This is not JSON:
var foo = {bar: 1};
Your code snippet is not using JSON at all and my educated guess is that you don't even need it. If you are using PHP to generate some JavaScript code, you can simply tweak your PHP code to print text that will contain real JavaScript variables. There is no need to encode stuff as plain text!
Now it's clear we don't need JSON, let's use a dirty trick. PHP has json_encode() and we can abuse the fact that a JSON strings resemble JavaScript variables. All we have to do is call json_encode() on our PHP variable and forget to quote the result:
<?php
$foo = array(
'bar' => 1,
'dot' => FALSE,
);
echo 'var JSONString = "' . json_encode($foo) . '";' . PHP_EOL;
echo 'var realVariable = ' . json_encode($foo) . ';' . PHP_EOL;
Compare:
var JSONString = "{"bar":1,"dot":false}";
var realVariable = {"bar":1,"dot":false};
Edit: Yep, my JSONString is not a valid string... but we get the idea <:-)

Returning JSON from PHP to JavaScript?

I have a PHP script that's being called through jQuery AJAX. I want the PHP script to return the data in JSON format to the javascript. Here's the pseudo code in the PHP script:
$json = "{";
foreach($result as $addr)
{
foreach($addr as $line)
{
$json .= $line . "\n";
}
$json .= "\n\n";
}
$json .= "}";
Basically, I need the results of the two for loops to be inserted in $json.
Php has an inbuilt JSON Serialising function.
json_encode
json_encode
Please use that if you can and don't suffer Not Invented Here syndrome.
Here are a couple of things missing in the previous answers:
Set header in your PHP:
header('Content-type: application/json');
echo json_encode($array);
json_encode() can return a JavaScript array instead of JavaScript object, see:
Returning JSON from a PHP Script
This could be important to know in some cases as arrays and objects are not the same.
There's a JSON section in the PHP's documentation. You'll need PHP 5.2.0 though.
As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.
If you don't, here's the PECL library you can install.
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>
Usually you would be interested in also having some structure to your data in the receiving end:
json_encode($result)
This will preserve the array keys as well.
Do remember that json_encode only works on utf8 -encoded data.
You can use Simple JSON for PHP. It sends the headers help you to forge the JSON.
It looks like :
<?php
// Include the json class
include('includes/json.php');
// Then create the PHP-Json Object to suits your needs
// Set a variable ; var name = {}
$Json = new json('var', 'name');
// Fire a callback ; callback({});
$Json = new json('callback', 'name');
// Just send a raw JSON ; {}
$Json = new json();
// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';
// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);
// Finally, send the JSON.
$Json->send();
?>
$msg="You Enter Wrong Username OR Password";
$responso=json_encode($msg);
echo "{\"status\" : \"400\", \"responce\" : \"603\", \"message\" : \"You Enter Wrong Username OR Password\", \"feed\":".str_replace("<p>","",$responso). "}";

Categories