Parsing JSON in PHP to extract lat/lon - php

I need to parse this JSON using PHP
[{
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.91138,
"lng": 7.671783
},
"name": "Corso Vinovo, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.909979,
"lng": 7.676234
},
"name": "Il Tempio del Pane, Corso Cesare Battisti, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.907805,
"lng": 7.674952
},
"name": "Banca Intesa, Via Ferdinando Salotto, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}]
to extract the coordinates in lat / lon.
What have I to use after
echo $wayPoints->?????
and how I create a for cicle to extract all the coordinates?
Any help will be appreciated!!Thank you!
Cesare
EDIT: a code sample (note that the JSON come from a POST parameter ...)
<?php
echo "Waypoints ...</br>";
echo "</br>";
echo $_POST['wayPoints'];
$wayPoints = $_POST['wayPoints'];
$json = json_decode($wayPoints);
foreach($json as $f){
echo $f['latLng']['lat'];
echo $f['latLng']['lng'];
}
?>
so should be more clear ... (the code NOT working ...)
Thank you again ...
EDIT 2: this code work !!!
<?php
echo "Waypoints ...</br>";
echo "</br>";
echo $_POST['wayPoints'];
$wayPoints = $_POST['wayPoints'];
$json = json_decode($wayPoints, true);
foreach($json as $f){
echo "</br>";
echo $f['latLng']['lat'];
echo "</br>";
echo $f['latLng']['lng'];
echo "</br>"; }
?>
the output is
44.91138
7.671783
44.909979
7.676234
44.907805
7.674952
Thank you all!

This will convert your json object into an associative array, then iterate with foreach.
//use json_decode in associative mode
$decoded = json_decode($json, true);
//Your object is now an array called $decoded
//Your locations are subarrays of $decoded
//The co-ords are subarrays of each $locationArray
foreach($decoded as $locationArray)
{
echo "The co-ordinates for {$locationArray['name']} are: {$locationArray['latLng']['lat']},{$locationArray['latLng']['lng']}" . PHP_EOL;
}

First you need to do $file = json_decode()
and then the file you get just add to foreach:
foreach($file as $f){
echo $f['latLng']['lat'];
echo $f['latLng']['lng'];
}

Related

Merge two JSONs php

I have 2 different jsons and I need to get one inside the other.
JSON 1
[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]
JSON 2
{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}
I need the second one inside the first one for use with javascript
I tried the array_merge() php function without getting results
since JSON1 is an array of JSON-object and JSON2 is just a JSON-object.
in addition to that you said, 'I need the second one inside the first one for use with javascript'. therefore, you can test this code https://3v4l.org/1HGNF/perf#output
please compare all performances in mem-usage and timing
$j1 = '[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]';
$j2 = '{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$j1 = json_decode($j1, true);
$j2 = json_decode($j2, true);
$j1[] = $j2;
var_dump(json_encode($j1));
You can use json_decode with parameter true to convert JSON into an array , then use array_merge to make them a single array
$j1 = '[{"id":"1","texto":"Vamos newells 17471934","fecha":"2019-06-24 12:09:12","categoria":"1","idpayment":"Reference_1561388952","provincia":"1","estado":"NO","email":"newells#gmail.com"}]';
$j1arr = json_decode($j1, true);
$j2 = ' {
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$j2arr = json_decode($j2, true);
$r = array_merge($j1arr[0], $j2arr);
You can use the merged array in javascript by using json_encode
json_encode($r)
https://3v4l.org/WKX1U
Do it simply like this way without any extra array merging methods-
<?php
$json1 = json_decode('[{"id":"1","texto":"Vamos newells 17471934","fecha":"2019-06-24 12:09:12","categoria":"1","idpayment":"Reference_1561388952","provincia":"1","estado":"NO","email":"newells#gmail.com"}]',1);
$json2 = json_decode('{"Texto":" VENDO O PERMUTO","imageJob":{"pathConvertido":"ClasificadosPNG/0011311247.png","convertido":true,"id":5011},"rubroClasificado":{"CodigoRubro":150,"id":76}}',1);
$json1[] = $json2; // add second json to first json
print_r($json1);
echo json_encode($json1);
?>
WORKING DEMO: https://3v4l.org/qhsJq
As you said you want to process the resulting data in JavaScript, and as per your question you want second json inside the first json. You can do something like this.
You will get a json as final result.
$first = '[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]';
$first = str_replace(['[',']','}'], '', $first);
$second = '{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$second = preg_replace('/\{/', ',', $second,1);
print_r($first.$second);
As result you will get a valid json, second json inside your first json, you can validate here

Decoding JSON SubArray PHP

I have looked around on Google for quite some time now, and I'm unable to find a solution that works for me.
I have this JSON Array:
[
{
"id": 1000,
"userIdent": "ABC1000",
"username": "john.doe",
"contacts": [
{
"id": 2000,
"clientId": 1000,
"email": "john.doe#example.com",
"phone": "",
"name": "",
"isBilling": false,
"isContact": false,
"types": [
{
"id": 3000,
"name": "Home contact"
}
]
}
]
}
]
and I have this PHP code:
$json = json_decode($response, true);
foreach($json as $item) {
echo $item['id'] . "<br>";
echo $item['userIdent'] . "<br>";
echo $item['contacts']['phone'] . "<br><br>";
foreach($json->contacts as $contacts) {
echo $contacts->phone;
echo $contacts['contacts']['phone'];
}
}
I have tried:
$item['contacts']['phone'];
$contacts->phone;
$contacts['contacts']['phone'];
I can't seem to be able to full any of the data from the sub-array "contacts". Any help would be greatly appreciated!
Note:- When you use true while using json_decode() it converts all json data to array(inner or outer). So you need to treat contacts as an array not an object.
So You need to iterate over $item['contacts'] array in the second foreach()
Do like below:-
$json = json_decode($response, true);
foreach($json as $item) {
echo $item['id'] . "<br>";
echo $item['userIdent'] . "<br>";
foreach($item['contacts'] as $contacts) {//treat contacts as an array not as an object
echo $contacts['phone'];
}
}
Output:- https://eval.in/952121 (i have taken phone number for testing purpose)
You have made a mistake, on your json, the contacts property is an array, so you can't access it (either in javascript or php) as an object with $contacts->contacts['phone'].
You should do something like that : $contacts->contacts[0]['phone'] or iterate other each contacts if there may be many.
Your code should look more like this
foreach($json as $item) { // 1
echo $item['id'] . "<br>";
echo $item['userIdent'] . "<br>";
foreach($item['contacts'] as $contact) { // 2
echo $contact['phone'];
}
}
So in the first foreach you start iterating over you entire array of items (1). Inside an item is an array contacts, so you start iterating over that with a new foreach (2). Each contact can be accessed directly inside the inner foreach.
Also, on decoding you said you wanted an array as output, so you should expect that and always access it like an array (square braces). If you would have gone for an object, the $contacts->phone syntax would work, but you shouldn't mix them like you are doing.
I hope this makes sense. Feel free to ask if not.

Parse a multi level json in php

I have this json file and I would like to get back "host_name" values for all items. Below, my php code, I tried some things, using true to decode json in an array or without it and use a foreach(), but I can't do it.
{
"href": "https://webservice:8080",
"items": [
{
"Hosts": {
"cluster_name": "cluster1",
"host_name": "server1"
},
"href": "https://server1:8080"
},
{
"Hosts": {
"cluster_name": "cluster1",
"host_name": "server2"
},
"href": "https://server2:8080"
},
{
"Hosts": {
"cluster_name": "cluster1",
"host_name": "server3"
},
"href": "https://server3:8080"
}
]
}
Here is my php code. Would like to do it as simple as possible. My goal is to use last values of a json ('host_name') to display all of them.
<?php
$content = file_get_contents("test.json");
$content = utf8_encode($content);
$result = json_decode($content, true);
var_dump($result);
echo "<br><br><br>";
#echo $result["items"]["Hosts"][0]["host_name"];
foreach($result as $r) {
echo $r['items']['Hosts']['cluster_name'].'<br>';
}
?>
Thanks.
You are just looping over the wrong array, it should be
foreach($result['items'] as $item) {
echo $item['Hosts']['host_name'];
}
$result need to be $result['items']
foreach($result['items'] as $r) {
echo $r['Hosts']['cluster_name'];
echo PHP_EOL;
}
Output:- https://eval.in/837593
As mentioned above, you are looping through the wrong array. You can loop through the object like this as well:
$obj = json_decode(utf8_encode(file_get_contents("test.json")));
foreach($obj->items as $item)
{
var_dump($item->Hosts->host_name);
}
Just to show an alternative method, you can use array_column() and implode() to omit the trailing <br> that will be displayed with the foreach loop methods.
Code: (Demo)
$items=json_decode($json,true)['items'];
echo implode("<br>",array_column(array_column($items,'Hosts'),'host_name'));
Output:
server1<br>server2<br>server3

Php loop with json coming back empty

what am i doing wrong here?
when i have only One result coming back this code works perfectly
$someObject = json_decode($data);
$id=$someObject->clips[0]->id;
but when i want to do a loop because i may get back 10 results this code is not working, i am sure i am missing something very simple here
$someObject = json_decode($data);
//var_dump($someObject);
foreach($someObject as $json){
echo $json->clips[0]->id;
}
EDIT:
this solution worked for anyone else who comes looking
foreach ($someObject->clips as $clip){
echo $clip->id. "<br>";
}
not sure how the other one answers the for loop issue i was having however.
You need to change this index [0] to dynamic index.
foreach($someObject as $k => $json){
echo $json->clips[$k]->id; // Insert $k here
}
change this
foreach($someObject as $json){
echo $json->clips[0]->id;
}
to
$i=0;
foreach($someObject as $json){
echo $json->clips[$i]->id;
$i++;
}
or as miken32 stated in the comment
foreach ($someObject->clips as $clip){
echo $clip->id;
}
read this reference: control-structures.foreach.php
in php array if you want to get all of items iterate you can use foreach
imaging you have this sample json:
{
"clips": [{
"id": 1,
"name": "test",
"tags": [
"tag1",
"tag2",
"tag3"
]
},
{
"id": 2,
"name": "test2",
"tags": [
"tag4",
"tag5",
"tag6"
]
}
]
}
if you want to get clips and tag list you can use this code:
<?php
$jsonText = '{"clips": [{"id": 1,"name": "test","tags": ["tag1","tag2","tag3"]},{"id": 2,"name": "test2","tags": ["tag4","tag5","tag6"]}]}';
$jsonObj = json_decode($jsonText);
// in this loop you can get clipObject
foreach($jsonObj->clips as $clipObj){
echo "clip id:" . $clipObj->id . "<br>\n";
echo "clip name:" . $clipObj->name. "<br>\n";
// in this loop you can get tags
foreach($clipObj->tags as $tag){
echo "clip tag:" . $tag. "<br>\n";
}
}

PHP code to READ JSON

I'm looking for a php code to read the JSON object (which I'm going to upload using Android into the url) and I also want the php function to insert the data into my db. Can someone please help me?
This is my JSON object
{
"id": "mID",
"description": "des",
"stars": "mStars",
"name": "avatar",
"year": "mYear",
"rating": "mRating",
"director": "mDirector"
"url": "www.dummy.com"
}
this is my php code
$app->post(
'/post/',
function () use ($app){
echo 'This is a POST route';
$json = $app->request->getBody();
$data = json_decode($json, true);
echo $data['name'];
echo $data['id'];
echo $data['description'];
echo $data['stars'];
echo $data['rating'];
echo $data['director'];
echo $data['url'];
echo $data['year'];
createMovie($data);
}
);
The following code is in a separate file. I have similar files with select statements which are working perfectly fine.
<?php
function createMovie($data) {
$conn=getDB();
if($stmt=$conn->prepare("$sql="INSERT INTO Movies (id, name,description, director, year, rating, stars, url)
VALUES ($data['id'],$data['name'],$data['description'],$data['director'],$data['year'],$data['rating'],$data['stars'],$data['url'])";
{
$stmt->execute();
$conn->close();
}
}
?>
when I type www.example.com/post/ I'm getting Error 404 not found
Use json_decode() like so:
<?php
$jsonData = '{ "user":"John", "age":22, "country":"United States" }';
$phpArray = json_decode($jsonData);
print_r($phpArray);
foreach ($phpArray as $key => $value) {
echo "<p>$key | $value</p>";
}
?>
Here is the link to the official documentation of the function.

Categories