As I read this Json in php? - php

I am starting my knowledge of php , I have difficulty reading this array in json , I can read all the information , but I can not read data off geofences array
How can read the information contained within " geoFences " id and name ?
My json example
I need read this in php json.
$response =
[
{
"id":441818,
"device":{
"id":6,
"uniqueId":"35390906000",
"name":"440",
"description":"COOR",
"timeout":3000,
"idleSpeedThreshold":0.0,
"iconType":{
"OFFLINE":{
"width":21,
"height":25,
"urls":[
"/img/marker-white.png",
"http://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/img/marker-green.png"
]
},
"LATEST":{
"width":21,
"height":25,
"urls":[
"http://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/img/marker.png",
"http://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/img/marker-green.png"
]
}
}
},
"time":"Fri, 07 Aug 2015 23:13:06 -0300",
"valid":true,
"latitude":-23.1,
"longitude":-46.1,
"altitude":745.0,
"speed":0.0,
"course":0.0,
"other":"\u003cinfo\u003e\u003cbattery\u003e58\u003c/battery\u003e\u003cip\u003e179.95.37.54\u003c/ip\u003e\u003c/info\u003e",
"geoFences":[
{
"id":16,
"name":"PL Eldorado",
"color":"20B2AA"
}
]
}
]
I need read in php this information...
"id":16,
"name":"PL Eldorado".
Example, if i need read device->name i do it:
$json=json_decode($response, true);
foreach ($json as $person_name => $person)
{
echo $person['device']['name'];
}
But i do it, don´t work.
$json=json_decode($response, true);
foreach ($json as $person_name => $person)
{
echo $person['geoFences']['id'];
echo $person['geoFences']['name'];
}

You have another array under geoFences.
This is the loop:
foreach($json as $person){
foreach($person['geoFences'] as $g){
echo $g['id'].'<br>';
echo $g['name'].'<br>';
}
}

Related

Adding key in an Array PHP

Im studying in array, and I was wondering How can I add key to this kind of array?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
because I needed convert the array to have a key base on the id inside the array.
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
and this is my code
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
I wanted to ask how can I put the id in the array? I cant use $cart_array['id'] = $value, it returns error.
Uncaught Error: Cannot use object of type stdClass as array
I could really use some explanation here
Following code can help you.
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
You don't have to loop at all. You can use array_column to make an array associative with one line of code.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
https://3v4l.org/cPD5n
You can use this code in your application to add keys to indexed array.
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
You can get same output json data as per you want :
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);

How to iterate JSON using PHP?

Can any one tell me how to iterate below given JSON data using PHP,
{
"value1":"3",
"value 2":"5",
"Id":[
"210",
"211"
]
}
<?php $json='{ "value1":"3", "value 2":"5", "Id":[ "210", "211" ] }';
$getarr=json_decode($json,true);
foreach( $getarr as $key => $value)
{
if(is_array($value))
{
// ID has an array so retrieve a value
foreach($value as $key1 => $value1)
{
echo $key."=>".$value1;
}
}else
{
echo $key."=>".$value;
}
} ?>
It will be produce the below output. Hope it will be helpful to solve your problem
Answer:
value1=>3 value 2=>5 Id=>210 Id=>211
Use json_decode function for converting it to array.
$array = json_decode( $json, true );
Copy and paste you can change the print out to fit your use
<?php
$bar=' { "value1":"3", "value 2":"5", "Id":[ "210", "211" ] }';
//var_dump($bar);
$JSONdata = json_decode($bar, true);
//echo
$JSONdataValue="";
$JSONdataValue.=$JSONdata['value1']."<br>";
$JSONdataValue.=$JSONdata['value 2']."<br>";
$JSONdataValue.=$JSONdata['Id'][0]."<br>";
$JSONdataValue.=$JSONdata['Id'][1]."<br>";
echo $JSONdataValue;
?>

Getting multiple keys' values from JSON with PHP

I am trying to extract team names, players name from this json. but get no resul.
My json file looks like. any idea where I am wrong ?
{"items":[
{"_id":305501,"id":"305501","created_at":"2015-10-19T19:57:02+13:00","updated_at":"2015-10-19T21:34:50+13:00","name":"Match in progress","verification_level":0,
"club_one":{"name":"Degree Club","id":14748,
"team":{"name":"Degree College XI","id":13009,"avatar":"/original/team/default_thumb.png",
"players":[
{"id":null,"name":"D Vinaya"},
{"id":617744,"name":"V Avika"},
{"id":617745,"name":"C Rumes"},
{"id":1360372,"name":"R Ferdo"}
],
"innings":[{"overs":34,"over_balls":0,"runs":99,"wickets":7}]
}
},
"club_two":{"name":"George Club","id":147736,
"team":{"name":"George College XI","id":154503,"avatar":"/original/team/default_thumb.png",
"players":[
{"id":null,"name":"M Premathe†"},
{"id":null,"name":"S Tion"},
{"id":null,"name":"N Perra"},
{"id":1400317,"name":"S Ren"}
],
"innings":[]
}
},
"processed":true,"visible":true,"match_level":{"name":null,"id":null}
}
],
"meta":{"total_pages":1}
}
and here is the php code.
$json_file = json_decode($load_json);
foreach ($items as $item) {
echo $item->$json_file->_id;
echo $item->$json_file->club_one;
echo $item->$json_file->club_two;
}
You are doing it wrong. As far as your json is concerned, loop it like this
$json_file = json_decode($json);
foreach ($json_file->items as $item) {
echo $item->id;
echo $item->club_one->name;
echo $item->club_two->name;
}

json decode - getting single array from object?

I have a json file which I decode using json_decode. The json file is an object which holds two arrays. I only want the first array but I'm having trouble figuring out how.
Json file
{
"app":{
"available":{
"stats":[
{
"name":"the name",
"at":"url"
},
{
"name":"the name",
"at":"url"
}
],
"stats2":[
{
"name":"the name",
"at":"url"
},
{
"name":"the name",
"at":"url"
}
]
}
}
}
I use
foreach($data3['app']['available'] as $name => $value)
{
foreach($value as $entry)
{
echo $entry['name'];
}
}
The output I get every name from both stats1 and stats2 arrays. I only want the names from stats1 array, not stats2. How can this be achieved?
because there are two arrays in app->available: stats and stats2
If you are interested in only stats, why don't you try:
foreach($data3['app']['available']['stats'] as $name => $value)
__UPDATE__
Try this one please
$in = '{"app":{"available":{"stats": [{"name":"the name","at":"url"},{"name":"the name", "at":"url"}],"stats2":[{"name":"the name","at":"url"},{"name":"the name","at":"url"}]}}}';
$obj = (array) json_decode($in, true);
foreach($obj['app']['available']['stats'] as $value)
{
foreach($value as $e => $v)
{
echo ($value['name'] );
echo ("\r");
}
}

Get data from JSON file with PHP [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 4 years ago.
I'm trying to get data from the following JSON file using PHP. I specifically want "temperatureMin" and "temperatureMax".
It's probably really simple, but I have no idea how to do this. I'm stuck on what to do after file_get_contents("file.json"). Some help would be greatly appreciated!
{
"daily": {
"summary": "No precipitation for the week; temperatures rising to 6° on Tuesday.",
"icon": "clear-day",
"data": [
{
"time": 1383458400,
"summary": "Mostly cloudy throughout the day.",
"icon": "partly-cloudy-day",
"sunriseTime": 1383491266,
"sunsetTime": 1383523844,
"temperatureMin": -3.46,
"temperatureMinTime": 1383544800,
"temperatureMax": -1.12,
"temperatureMaxTime": 1383458400,
}
]
}
}
Get the content of the JSON file using file_get_contents():
$str = file_get_contents('http://example.com/example.json/');
Now decode the JSON using json_decode():
$json = json_decode($str, true); // decode the JSON into an associative array
You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:
echo '<pre>' . print_r($json, true) . '</pre>';
This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true in order to let print_r() know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:
$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];
Or loop through the array however you wish:
foreach ($json['daily']['data'] as $field => $value) {
// Use $field and $value here
}
Demo!
Use json_decode to transform your JSON into a PHP array. Example:
$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b
Try:
$data = file_get_contents ("file.json");
$json = json_decode($data, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br/>';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br/>';
}
}
}

Categories