<?php
$url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=YOURAPI";
$json = file_get_contents($url);
$data = json_decode($json, true);
$data['city']['name'];
foreach ($data['list'] as $day => $value) {
echo $todaystemperature = $value[temp][max];
}
?>
This has been working suddenly stopped working some reason. I keep getting on file_get_contents. Not sure what make this code mess
The JSON Data needs to be parsed based on the JSON response that you are getting.
Steps for Getting the Json Data using PHP
First you have to get the data has the json_response.
Then you have to make the json response to decode through the json code using json_decode($json,TRUE)
After that you can use foreach() for splitting up of the array that you get based on the decoded value.
While running the above URL that you have given in the code i am getting the output as follows.
Obtained JSON:
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"base":"stations","main":{"temp":284.66,"pressure":1016.88,"humidity":68,"temp_min":284.66,"temp_max":284.66,"sea_level":1024.55,"grnd_level":1016.88},"wind":{"speed":4.91,"deg":97.501},"clouds":{"all":92},"dt":1476377768,"sys":{"message":0.1769,"country":"GB","sunrise":1476339772,"sunset":1476378552},"id":2643743,"name":"London","cod":200}
Hence after following up the process you can get the values like this.
PHP Code:
<?php
$url = "http://api.openweathermap.org/data/2.5/weather? q=London,uk&appid=a1fc2c19d548237a56e0edd7b79b3ebc";
$json = file_get_contents($url);
$data = json_decode($json, true);
echo $temp = $data['main']['temp']; // To convert the data to Celsius by hitting the API called api.openweathermap.
?>
Note: $data['main']['temp'] - Make sure that you get data over here and then you will succeed over here.
Output for the Json Parse is as follows for the above obtained JSON:
String Parse:
{
"coord":{
"lon":-0.13,"lat":51.51},"weather":[
{
"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"base":"stations","main":{
"temp":284.66,"pressure":1016.88,"humidity":68,"temp_min":284.66,"temp_max":284.66,"sea_level":1024.55,"grnd_level":1016.88},"wind":{
"speed":4.91,"deg":97.501},"clouds":{
"all":92},"dt":1476377768,"sys":{
"message":0.1769,"country":"GB","sunrise":1476339772,"sunset":1476378552},"id":2643743,"name":"London","cod":200
}
Js Eval:
{
"coord":{
"lon":-0.13,"lat":51.51},"weather":[
{
"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"base":"stations","main":{
"temp":284.66,"pressure":1016.88,"humidity":68,"temp_min":284.66,"temp_max":284.66,"sea_level":1024.55,"grnd_level":1016.88},"wind":{
"speed":4.91,"deg":97.501},"clouds":{
"all":92},"dt":1476377768,"sys":{
"message":0.1769,"country":"GB","sunrise":1476339772,"sunset":1476378552},"id":2643743,"name":"London","cod":200
}
Hence when you do the json_decode() for the above obtained JSON string you have the out put as follows.
array (
'coord' =>
array (
'lon' => -0.13000000000000000444089209850062616169452667236328125,
'lat' => 51.50999999999999801048033987171947956085205078125,
),
'weather' =>
array (
0 =>
array (
'id' => 804,
'main' => 'Clouds',
'description' => 'overcast clouds',
'icon' => '04d',
),
),
'base' => 'stations',
'main' =>
array (
'temp' => 284.66000000000002501110429875552654266357421875,
'pressure' => 1016.8799999999999954525264911353588104248046875,
'humidity' => 68,
'temp_min' => 284.66000000000002501110429875552654266357421875,
'temp_max' => 284.66000000000002501110429875552654266357421875,
'sea_level' => 1024.549999999999954525264911353588104248046875,
'grnd_level' => 1016.8799999999999954525264911353588104248046875,
),
'wind' =>
array (
'speed' => 4.910000000000000142108547152020037174224853515625,
'deg' => 97.501000000000004774847184307873249053955078125,
),
'clouds' =>
array (
'all' => 92,
),
'dt' => 1476377768,
'sys' =>
array (
'message' => 0.176900000000000001687538997430237941443920135498046875,
'country' => 'GB',
'sunrise' => 1476339772,
'sunset' => 1476378552,
),
'id' => 2643743,
'name' => 'London',
'cod' => 200,
)
Hence after getting the array it seems to be of Single Object with array for some of the keys that has been obtained.
Hence you can fetch the data only from this output obtained using the loop operators called foreach(). Hence by using the foreach() the array data will be coming in the loop as single manner and then it will manipulate the result.
your code seems not right, the url you are using is giving following response
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04d"
}
],
"base": "stations",
"main": {
"temp": 284.66,
"pressure": 1016.88,
"humidity": 68,
"temp_min": 284.66,
"temp_max": 284.66,
"sea_level": 1024.55,
"grnd_level": 1016.88
},
"wind": {
"speed": 4.91,
"deg": 97.501
},
"clouds": {
"all": 92
},
"dt": 1476377646,
"sys": {
"message": 0.0048,
"country": "GB",
"sunrise": 1476339772,
"sunset": 1476378553
},
"id": 2643743,
"name": "London",
"cod": 200
}
In the above json response i can not find any key with 'list' that is why your code breaks. This code should be fine to get the temp of the city
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=a1fc2c19d548237a56e0edd7b79b3ebc";
$json = file_get_contents($url);
$data = json_decode($json, true);
echo $temp = $data['main']['temp'];
?>
$json = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=a1fc2c19d548237a56e0edd7b79b3ebc');
$data = json_decode($json,true);
OR
$data = json_decode($json);
echo "<pre>";
print_r($data);
exit;
Here is the result
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=imperial&cnt=1&lang=en&appid=YOURAPI";
$json = file_get_contents($url);
$data = json_decode($json, true);
echo $temp = $data['main']['temp'];
?>
Related
im having some issues adding a new item to an associative array,
This is how i'm creating my structure:
$cpdata[$count] = array(
'value' => $value->value,
'images' => array(
'color' => $value->color,
'image' => $value->image,
),
);
and this is how it looks like when i output like a json:
{
"value": "BOX",
"images": {
"color": "white",
"image": "white.png"
}
}
But i would like to add more items to images somthing like this:
{
"value": "BOX",
"images": [
{
"color": "white",
"image": "white.png"
},
{
"color": "black",
"image": "black.png"
},
{
"color": "gray",
"image": "gray.png"
}
]
}
I've tried with array_push and array_merge but i cant get it
i've tried array_push($cpdata['images'][$count]['images'], 'color'=>'red', image' => 'red.png')
Could you please help me?
Regards
Mario
In context of PHP, what you have there is a JSON variable. If that is coming to you as a string you'll have to decode it first using json_decode($string);
Then you can set up an object, populate it with the image variables and write it back to the $json object as an array, like:
<?php
// example code
$json = <<<EOT
{
"value": "BOX",
"images": {
"color": "white",
"image": "white.png"
}
}
EOT;
$json = json_decode($json);
$i = new stdClass;
$i->color = $json->images->color;
$i->image = $json->images->image;
$json->images = array($i);
After that you can push to it like
$newimage = new stdClass;
$newimage->color = "foo";
$newimage->image = "bar";
$json->images[] = $newimage;
output
print_r($json);
stdClass Object
(
[value] => BOX
[images] => Array
(
[0] => stdClass Object
(
[color] => white
[image] => white.png
)
[1] => stdClass Object
(
[color] => foo
[image] => bar
)
)
)
example https://www.tehplayground.com/oBS1SN1ze1DsVmIn
Before converting into json
$cpdata[$count] = array(
'value' => $value->value,
'images' => array(
'color' => $value->color,
'image' => $value->image,
),
);
// Cpdata array has $count which has `images` as an array and we want to push another element(array) into images array
array_push($cpdata[$count]['images'], ['color'=>'red', 'image' => 'red.png']);
I get some data from an API call and I try to construct a JSON to send it back to another API.
The final JSON must look like this:
{
"jobs": {
"MP_OFFER_ID_1": {
"job_id": "jobboard_reference_1",
"url": "url_1",
"status": 0
},
"MP_OFFER_ID_2": {
"job_id": "job_id_2",
"url": "url_2",
"status": 1
},
}
}
So under the jobs key, it's not an array of elements but a list of elements with unique keys.
And that's what I'm having trouble to get.
The data I want to parse is in an array structured like this:
Array(
[0] => Array(
[link] => some-url
[id] => 18790674
[ref] => 0015909-18790674
)
// ...
);
link has to be placed in the url key of the JSON.
id is the JSON key, in the examples it's MP_OFFER_ID_1 etc
ref has to be placed in job_id
I actually have this JSON at the end:
{
"jobs": [
[
{
"18790674": {
"job_id": "0015909-18790674",
"url": "test",
"status": 1
}
},
{
"18790678": {
"job_id": "0015892-18790678",
"url": "test",
"status": 1
}
}
]
]
}
As you can see, jobs is an array (actually it's an array of array ^^) and that's not what I want here...
I came up with this, but it was very difficult to understand what exactly you want from the very limited info in question:
<?php
$input = [
[
'id' => 18790674,
'link' => 'some-url',
'ref' => '0015909-18790674',
],
[
'id' => 18790678,
'link' => 'another-url',
'ref' => '0015909-18790678',
],
];
$output = new stdClass();
foreach ($input as $arr) {
$obj = new stdClass();
$key = $arr['id'];
$obj->job_id = $arr['id'];
$obj->url = $arr['link'];
$obj->status = '1'; // ?
$output->{$key} = $obj;
}
echo json_encode($output, JSON_PRETTY_PRINT);
Output:
{
"18790674": {
"job_id": 18790674,
"url": "some-url",
"status": "1"
},
"18790678": {
"job_id": 18790678,
"url": "another-url",
"status": "1"
}
}
foreach ($ordersList as $object) {
$entityid = $object->entity_id; //how to give this $entityid with in json
$json='{
"orderNo":$entityid, //here i want to assign the value of $entityid
"customerCode": $customerid,
"dateOrdered": "08-07-2015",
"warehouseId" : ,
"orderLineList":
[
"productId": 1000002,
"qty": 6,
"price": 10
]
}';
}
$data = json_decode($json);
$data_string= json_encode($data);
Don't write JSON strings by hand.
$data = [
"orderNo" => $entityid, //here i want to assign the value of $entityid
"customerCode" => $customerid,
"dateOrdered" => "08-07-2015",
"warehouseId" => null ,
"orderLineList" => [
"productId": 1000002,
"qty": 6,
"price": 10,
],
];
$json = json_encode($data);
json_decode() would give an error for this:
{"orderLineList": [ "productId": 1000002 ]}
Try this code:
foreach ($ordersList as $object) {
//Start with a PHP array
//Don't mess with concatenation, you will get tangled with opening & closing quotes.
//If your information comes in a json format. Use json_decode() to convert it into a PHP array.
//$dateOrder,$warehouseId,$object->customer_id are fictious variables. Replace them with real values.
$orderArray[] = [
'orderNo' => $object->entity_id,
'customerCode' => $object->customer_id,
'dateOrdered' => $dateOrdered,
'warehouseId' => $warehouseId,
'orderLineList' => [
'productId': 1000002,
'qty': 6,
'price': 10
]
];
}
$data_string = json_encode($orderArray);
I have two arrays (this is an JSON array from PHP)
one
"result1": [
{
"driverId": "3",
"latitude": "23.752182",
"longitude": "90.377730",
"distance": "0.00011211999971692422",
"EstTime": 137
},
{
"driverId": "4",
"latitude": "23.75182",
"longitude": "90.3730",
"distance": "0.000171692422",
"EstTime": 111
}
]
Two
"result2": [
{
"driverId": "3"
}
]
I want to compare these arrays. if any result1 item driverID matches any item of result2 then skip that item from result1
You can do this in two stages.
First gather the driverIds to exclude using array_map
$exclude = array_map(
function($v) {
return $v['driverId'];
},
$json['result2']
);
Then use array_filter to filter out those elements you do not want:
$result = array_filter(
$json['result1'],
function($a) use ($exclude) {
return !in_array($a['driverId'], $exclude);
}
);
I have tested this with the following code. If you have separate arrays, just supply them independently above instead of using $json['result1'].
$a = <<<JSON
{
"result1": [
{
"driverId": "3",
"latitude": "23.752182",
"longitude": "90.377730",
"distance": "0.00011211999971692422",
"EstTime": 137
},
{
"driverId": "4",
"latitude": "23.75182",
"longitude": "90.3730",
"distance": "0.000171692422",
"EstTime": 111
}
],
"result2": [
{
"driverId": "3"
}
]
}
JSON;
$json = json_decode($a, true);
Try the following. In this answer I am assuming that you have already applied json_decode() and extracted $result1 and $result2 into PHP arrays.
Further to your last comment, code edited to work in version 5.2
<?php
// associative array of result1
$result1 = array(
array(
'driverId' => '3',
'latitude' => '23.752182',
'longitude' => '90.377730',
'distance' => '0.00011211999971692422',
'EstTime' => 137
),
array(
'driverId' => '4',
'latitude' => '23.75182',
'longitude' => '90.3730',
'distance' => '0.000171692422',
'EstTime' => 111
)
);
// associative array of result2
$result2 = array(
array(
'driverId' => '3'
)
);
// first, let's get a list of ids that we want to exclude
// run array map over the result2 and return the ids - this
// creates an array of "exclusion" ids. Note you could use
// foreach here also.
function pluckResultIds($result) {
return $result['driverId'];
}
$excludeIds = array_map('pluckResultIds', $result2);
var_dump($excludeIds); // result: array(3)
// next let's use array_filter to run over result1. for each
// entry in result1 - we check if the current driverId is in
// the exclusion array - if it is *not* we return the current
// this creates a new array $filtered containing only the
// filtered elements that do not match
$filtered = array();
foreach ($result1 as $result) {
$id = $result['driverId'];
if (!in_array($id, $excludeIds)) {
$filtered[] = $result;
}
};
var_dump($filtered);
Yields:
array (size=1)
1 =>
array (size=5)
'driverId' => string '4' (length=1)
'latitude' => string '23.75182' (length=8)
'longitude' => string '90.3730' (length=7)
'distance' => string '0.000171692422' (length=14)
'EstTime' => int 111
Hope this helps! :)
I want to create a array for the following json code.
{
"homeMobileCountryCode": 310,
"homeMobileNetworkCode": 260,
"radioType": "gsm",
"carrier": "T-Mobile",
"cellTowers": [
{
"cellId": 39627456,
"locationAreaCode": 40495,
"mobileCountryCode": 310,
"mobileNetworkCode": 260,
"age": 0,
"signalStrength": -95
}
],
"wifiAccessPoints": [
{
"macAddress": "01:23:45:67:89:AB",
"signalStrength": 8,
"age": 0,
"signalToNoiseRatio": -65,
"channel": 8
},
{
"macAddress": "01:23:45:67:89:AC",
"signalStrength": 4,
"age": 0
}
]
}
I have tried with the following but it is showing parsing error in google maps geomatic api
$a = array("homeMobileCountryCode" => 310,
"homeMobileNetworkCode" => 260,
"radioType" => "gsm",
"carrier" => "T-Mobile");
$jsonVal = json_encode($a);
can anyone help me?
PHP's json_encode does not wrap integers with double quotes, which is invalid json. Try this:
$a = array("homeMobileCountryCode" => "310",
"homeMobileNetworkCode" => "260",
"radioType" => "gsm",
"carrier" => "T-Mobile");
$jsonVal = json_encode($a);
From json to Array:
$array = json_decode(/* json text /*);
From Array to Json
$json = json_encode(/* array Object */);
explanations here but you can skip to clean final code further down.
$cellTower1 = array( "cellId"=> "39627456",
"locationAreaCode"=> "40495",
"mobileCountryCode"=> "310",
"mobileNetworkCode"=> "260",
"age"=> "0",
"signalStrength"=> "-95" );
$cellTower2 = array( "cellId"=> "2222222",
"locationAreaCode"=> "22222",
"mobileCountryCode"=> "222",
"mobileNetworkCode"=> "222",
"age"=> "22",
"signalStrength"=> "-22" );
Then combine all cell towers
$allCellTowers[] = $cellTower1;
$allCellTowers[] = $cellTower2;
//etc... or could be in a loop
Now for MAC addresses and wifiAccessPoints.
$macAddress1 = array (
"macAddress"=> "01:23:45:67:89:AB",
"signalStrength" => "8",
"age" => "0",
"signalToNoiseRatio" => "-65",
"channel" => "8"
);
$macAddress2 = array (
"macAddress" => "01:23:45:67:89:AC",
"signalStrength" => "4",
"age" => "0"
);
$macAddress3 = etc...
just as for cellTower1, cellTower2 the macaddresses 1 & 2 above can be populated with a loop.
Adding them to wifiAccessPoints also can be done in a loop but it done manually below just so you understand.
$wifiAccessPoints[] = $macAddress1;
$wifiAccessPoints[] = $macAddress2;
finally the other elements all go in the resulting array to encode
$myarray = array( "homeMobileCountryCode"=> "310",
"homeMobileNetworkCode"=> "260",
"radioType"=> "gsm",
"carrier"=> "T-Mobile",
"cellTowers"=>$allCellTowers,
"wifiAccessPoints" => $wifiAccessPoints
);
$json = json_encode($myarray);
IN CLEAN CODE IT IS
$cellTower1 = array( "cellId"=> "39627456",
"locationAreaCode"=> "40495",
"mobileCountryCode"=> "310",
"mobileNetworkCode"=> "260",
"age"=> "0",
"signalStrength"=> "-95" );
$allCellTowers[] = $cellTower1;
$macAddress1 = array (
"macAddress"=> "01:23:45:67:89:AB",
"signalStrength" => "8",
"age" => "0",
"signalToNoiseRatio" => "-65",
"channel" => "8"
);
$macAddress2 = array (
"macAddress" => "01:23:45:67:89:AC",
"signalStrength" => "4",
"age" => "0"
);
$wifiAccessPoints[] = $macAddress1;
$wifiAccessPoints[] = $macAddress2;
$myarray = array( "homeMobileCountryCode"=> "310",
"homeMobileNetworkCode"=> "260",
"radioType"=> "gsm",
"carrier"=> "T-Mobile",
"cellTowers"=>$allCellTowers,
"wifiAccessPoints" => $wifiAccessPoints
);
//note that you have your first key missing though in your example
$json = json_encode($myarray);