PHP: Accessing data within complex json - php

I am currently working on a Joomla module and as alternative to the discontinued yahoo finance, i had decided to use API from ietrading such as which gives data as showing below:
sample extract: readable output of print_r($json):
{
"AAPL": {
"quote": {
"symbol": "AAPL",
"companyName": "Apple Inc.",
"primaryExchange": "Nasdaq Global Select",
"sector": "Technology",
"calculationPrice": "tops",
"open": 162.62,
...
"week52High": 183.5,
"week52Low": 142.2,
"ytdChange": -0.04610909853958216
}
},
"FB": {
"quote": {
"symbol": "FB",
"companyName": "Facebook Inc.",
"primaryExchange": "Nasdaq Global Select",
"sector": "Technology",
"calculationPrice": "tops",
"open": 160.07,
"openTime": 1524663000827,
"close": 159.69,
"closeTime": 1524686400183,
"high": null,
"low": null,
"latestPrice": 173.19,
...
"week52High": 195.32,
"week52Low": 144.4216,
"ytdChange": -0.11977731231396754
}
}
}
The issue for me is how to access the data of quote within each index with output as follows:
AAPL : Apple Inc.
FB : Facebook Inc.
The only time it worked is if I do something like this:
$test_data = file_get_contents('data.json');
$json = json_decode($test_data,true);
$jsonData[] = "";
foreach($json as $item){
$allItems[] = $item;
}
var_dump($allItems);
for ($i=0; $i < COUNT($allItems); $i++) {
$jsonData[]= $allItems[$i]['quote'];
echo $jsonData[$i+1]['companyName'].' - from all for<br/>';
}
echo "<h2>Testing</h2>";
echo $jsonData[1]['symbol'].' : '.$jsonData[1]['companyName'].'<br/>';
echo $jsonData[2]['symbol'].' : '.$jsonData[2]['companyName'].'<br/>';
I believe there is an optimise way of doing this.
print_r($json) as adviced
`'Array ( [AAPL] => Array ( [quote] => Array ( [symbol] => AAPL [companyName] => Apple Inc. [primaryExchange] => Nasdaq Global Select [sector] => Technology [calculationPrice] => tops [open] => 162.62 [openTime] => 1524663000142 [close] => 163.65 [closeTime] => 1524686400487 [high] => [low] => [latestPrice] => 164.57 [latestSource] => IEX real time price [latestTime] => 9:35:46 AM [latestUpdate] => 1524749746099 [latestVolume] => 1354291 [iexRealtimePrice] => 164.57 [iexRealtimeSize] => 100 [iexLastUpdated] => 1524749746099 [delayedPrice] => 164.28 [delayedPriceTime] => 1524748852180 [previousClose] => 163.65 [change] => 0.92 [changePercent] => 0.00562 [iexMarketPercent] => 0.01142 [iexVolume] => 15466 [avgTotalVolume] => 32759551 [iexBidPrice] => 164.61 [iexBidSize] => 100 [iexAskPrice] => 165.07 [iexAskSize] => 100 [marketCap] => 835030319410 [peRatio] => 16.91 [week52High] => 183.5 [week52Low] => 142.2 [ytdChange] => -0.046109098539582 ) ) [FB] => Array ( [quote] => Array ( [symbol] => FB [companyName] => Facebook Inc. [primaryExchange] => Nasdaq Global Select [sector] => Technology [calculationPrice] => tops [open] => 160.07 [openTime] => 1524663000827 [close] => 159.69 [closeTime] => 1524686400183 [high] => [low] => [latestPrice] => 173.19 [latestSource] => IEX real time price [latestTime] => 9:35:55 AM [latestUpdate] => 1524749755278 [latestVolume] => 13276538 [iexRealtimePrice] => 173.19 [iexRealtimeSize] => 100 [iexLastUpdated] => 1524749755278 [delayedPrice] => 172.53 [delayedPriceTime] => 1524748852406 [previousClose] => 159.69 [change] => 13.5 [changePercent] => 0.08454 [iexMarketPercent] => 0.02455 [iexVolume] => 325939 [avgTotalVolume] => 48329785 [iexBidPrice] => 173.04 [iexBidSize] => 200 [iexAskPrice] => 173.22 [iexAskSize] => 100 [marketCap] => 502140357915 [peRatio] => 28.16 [week52High] => 195.32 [week52Low] => 144.4216 [ytdChange] => -0.11977731231397 ) ) )'`

here is a short method to do that :
in this example , i'm using the foreach loop instead of loop with index . this make you iterate on your array object by object and filtering data as you want .
<?php
//Enter your code here, enjoy!
$data = ' {
"AAPL": {
"quote": {
"symbol": "AAPL",
"companyName": "Apple Inc.",
"primaryExchange": "Nasdaq Global Select",
"sector": "Technology",
"calculationPrice": "tops",
"open": 162.62,
"week52High": 183.5,
"week52Low": 142.2,
"ytdChange": -0.04610909853958216
}
},
"FB": {
"quote": {
"symbol": "FB",
"companyName": "Facebook Inc.",
"primaryExchange": "Nasdaq Global Select",
"sector": "Technology",
"calculationPrice": "tops",
"open": 160.07,
"openTime": 1524663000827,
"close": 159.69,
"closeTime": 1524686400183,
"high": null,
"low": null,
"latestPrice": 173.19,
"week52High": 195.32,
"week52Low": 144.4216,
"ytdChange": -0.11977731231396754
}
}
}';
$json = json_decode($data,true);
foreach($json as $key => $object){
echo $key ." : ". $object['quote']['companyName']."</br>";
}
result :
AAPL : Apple Inc.
FB : Facebook Inc.
i hope that help you .

Related

Simplify & Optimize PHP Array

I am working on combining the array into a key with the count of repeated "option""code". My Request JSON is like this
[{
"productId": "DENSUS-MARK",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE"
},
{
"code": "HIGLIGT_OPTION_HANDLE1"
}
]
},
{
"productId": "DENSUS-MARK",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE"
}
]
},
{
"productId": "DENSUS-MARK-II",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE"
}
]
}]
After combing the "productID" and the count of ["options"]["code"] (For ProductId - DENSUS-MARK, the code "HIGLIGT_OPTION_HANDLE" count is 2. So I am getting a output like this.
{
"productId": "DENSUS-MARK",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE",
"count": 2
},
{
"code": "HIGLIGT_OPTION_HANDLE1",
"count": 1
}
]
},
{
"productId": "DENSUS-MARK-II",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE",
"count": 1
}
]
}
}
This is my current php code and I need to optimize & simply this below code
$datas = json_decode($arr,true);
$formattedData = [];
foreach ($datas as $f) {
foreach ($f['options'] as $option) {
$formattedData[$f['productID']]['productID'] = $f['productID'];
$formattedData[$f['productID']]['options']['code'][$option['code']][] = $option['code'];
}
}
foreach ($formattedData as &$data) {
$formattedOptions = [];
foreach ($data['options']['code'] as $key => $codes) {
$formattedOptions[] = [
'code' => $key,
'count' => count($codes)
];
}
$data = $formattedOptions;
}
print_r($formattedData);
Someone, could you please help me in this.
I don't know if this is the optimization you want. Meanwhile, less than two loops, I have not found. It's not quite the expected result, but you should be able to fix it if you need to.
With:
$input = array (
0 =>
array (
'productId' => 'DENSUS-MARK',
'options' =>
array (
0 =>
array (
'code' => 'HIGLIGT_OPTION_HANDLE',
),
1 =>
array (
'code' => 'HIGLIGT_OPTION_HANDLE1',
),
),
),
1 =>
array (
'productId' => 'DENSUS-MARK',
'options' =>
array (
0 =>
array (
'code' => 'HIGLIGT_OPTION_HANDLE',
),
),
),
2 =>
array (
'productId' => 'DENSUS-MARK-II',
'options' =>
array (
0 =>
array (
'code' => 'HIGLIGT_OPTION_HANDLE',
),
),
)
);
Then just:
$result = [];
foreach($input as $row) {
foreach($row['options'] as $value) {
$result[$row['productId']][$value['code']] ??=0;
$result[$row['productId']][$value['code']] += count($value);
}
}
var_export($result);
Results:
array (
'DENSUS-MARK' =>
array (
'HIGLIGT_OPTION_HANDLE' => 2,
'HIGLIGT_OPTION_HANDLE1' => 1,
),
'DENSUS-MARK-II' =>
array (
'HIGLIGT_OPTION_HANDLE' => 1,
),
)

Difficulty to understand PHP POST to REST API - mixed array and objects

I'm trying to POST data to a REST API.
On Postman I can POST with success, the JSON body is:
{
"version": 0,
"roles": {
"customer": {
}
},
"person": {
"firstName": "Inge",
"lastName": "Musterfrau"
},
"emailAddresses" :{
"private" : [
"email#domain.com"
]
},
"addresses": {
"billing": [
{
"supplement": null,
"street": "aaa",
"zip": "12345",
"city": "Berlin",
"countryCode": "DE"
}
]
}
}
My problem is on addresses billing. I don't know how to create the object/array correctly so the API accept it.
I'm build the parameters on PHO like bellow:
$billingAddr = array(
"supplement" => $billingAddress["streetDetails"],
"street" => $billingAddress["street"],
"zip" => $billingAddress["zipCode"],
"city" => $billingAddress["city"],
"countryCode" => $billingAddress["country"],
);
$params = [
"version" => 0,
"roles" => $roles,
"person" => $person,
"emailAddresses" => $emailAddresses,
"addresses" => [
"billing" => $billingAddr
]
];
I get an error: "missing_entity - addresses - validation_failure".
I believe my issue is creating the mixed Object addresses, array billing.
So, going strictly by the PHP example, doing a json_encode'd output of that shows that the structure is not quite the same at the addresses.
Note that I do not have the data for most of the rest of the json info from the PHP example, so the output examples below are strictly focused on the addresses section.
Before JSON change:
echo json_encode($params, JSON_PRETTY_PRINT);
{
"version": 0,
"roles": null,
"person": null,
"emailAddresses": null,
"addresses": {
"billing": {
"supplement": null,
"street": null,
"zip": null,
"city": null,
"countryCode": null
}
}
}
... in that, note that the billing does not have the [] characters like what is sent using postman.
No worries though, it's an easy fix. The addresses part should be changed to get an array of billing addresses, like so:
"addresses" => [
"billing" => [$billingAddr]
]
Then running a recheck with that change applied shows:
After JSON change:
echo json_encode($params, JSON_PRETTY_PRINT);
{
"version": 0,
"roles": null,
"person": null,
"emailAddresses": null,
"addresses": {
"billing": [
{
"supplement": null,
"street": null,
"zip": null,
"city": null,
"countryCode": null
}
]
}
}
That should help to achieve the expected format.
Here's the fiddle example in case you might need another PHP version to check. The fiddle default is 8.0.1
Object properties and associative arrays are easy to access/declare directly; however, when you need to push data into indexed subarrays, you can to use [] syntax or array_push().
If you want to build a bit more maintainability in this code, you can build the variable-length subarrays as individual variables and then feed them into the master array just before json_encoding.
$version = 0;
$roles = ['customer' => []];
$person = [
'firstName' => 'Inge',
'lastName' => 'Musterfrau'
];
$emailAddresses = [
'private' => [
'email#domain.com',
]
];
$billingAddresses[] = [
'supplement' => $billingAddress["streetDetails"],
'street' => $billingAddress["street"],
'zip' => $billingAddress["zipCode"],
'city' => $billingAddress["city"],
'countryCode' => $billingAddress["country"]
];
// use $billingAddresses[] again to push another subarray into $billing
$data = [
'version' => $version,
'roles' => $roles,
'person' => $person,
'emailAddresses' => $emailAddresses,
'addresses' => [
'billing' => $billingAddresses
]
]
This will create your array/json :
$arr['version'] = "0";
$arr['roles']['customer'] = [];
$arr['person']['firstName'] = "Inge";
$arr['person']['lastName'] = "Musterfrau";
$arr['emailAddresses']['private'][] = "email#domain.com";
$arr['addresses']['billing'][0]['supplement'] = "";
$arr['addresses']['billing'][0]['street'] = "aaa";
$arr['addresses']['billing'][0]['zip'] = "12345";
$arr['addresses']['billing'][0]['city'] = "Berlin";
$arr['addresses']['billing'][0]['countryCode'] = "DE";
$newJson = json_encode($arr);
Afterwards you json_encode it and voila the perfect json and very simple!
The best and easiest way to look at a json (to my opinion at least:) is as an array! (no shame in using the browser and echo "<pre>" here!) - We'll build an identical array and json it up back!
Once we see the json as an array we build the same in a very simple way here is the whole code example with step by step:
<?php
/*Our original json */
$json = '{
"version": 0,
"roles": {
"customer": {
}
},
"person": {
"firstName": "Inge",
"lastName": "Musterfrau"
},
"emailAddresses" :{
"private" : [
"email#domain.com"
]
},
"addresses": {
"billing": [
{
"supplement": null,
"street": "aaa",
"zip": "12345",
"city": "Berlin",
"countryCode": "DE"
}
]
}
}';
$array = json_decode($json,true);
echo '<pre>';
/* original array */
echo "original array: ";
print_r($array);
echo '<pre>';
/* now lets create the same array with less fuss?! */
$arr['version'] = "0";
$arr['roles']['customer'] = [];
$arr['person']['firstName'] = "Inge";
$arr['person']['lastName'] = "Musterfrau";
$arr['emailAddresses']['private'][] = "email#domain.com";
$arr['addresses']['billing'][0]['supplement'] = "";
$arr['addresses']['billing'][0]['street'] = "aaa";
$arr['addresses']['billing'][0]['zip'] = "12345";
$arr['addresses']['billing'][0]['city'] = "Berlin";
$arr['addresses']['billing'][0]['countryCode'] = "DE";
/* the new array: */
echo "our newly created array: ";
echo '<pre>';
print_r($arr);
echo '<pre>';
/* back to json */
echo "new Json: ";
echo '<pre>';
$newJson = json_encode($arr);
print_r($newJson);
This will return:
original array: Array
(
[version] => 0
[roles] => Array
(
[customer] => Array
(
)
)
[person] => Array
(
[firstName] => Inge
[lastName] => Musterfrau
)
[emailAddresses] => Array
(
[private] => Array
(
[0] => email#domain.com
)
)
[addresses] => Array
(
[billing] => Array
(
[0] => Array
(
[supplement] =>
[street] => aaa
[zip] => 12345
[city] => Berlin
[countryCode] => DE
)
)
)
)
our newly created array:
Array
(
[version] => 0
[roles] => Array
(
[customer] => Array
(
)
)
[person] => Array
(
[firstName] => Inge
[lastName] => Musterfrau
)
[emailAddresses] => Array
(
[private] => Array
(
[0] => email#domain.com
)
)
[addresses] => Array
(
[billing] => Array
(
[0] => Array
(
[supplement] =>
[street] => aaa
[zip] => 12345
[city] => Berlin
[countryCode] => DE
)
)
)
)
new Json:
{"version":"0","roles":{"customer":[]},"person":{"firstName":"Inge","lastName":"Musterfrau"},"emailAddresses":{"private":["email#domain.com"]},"addresses":{"billing":[{"supplement":"","street":"aaa","zip":"12345","city":"Berlin","countryCode":"DE"}]}}
Building arrays can be very simple this way - almost feels linear! :)

Display data from two arrays having one common point

I have two arrays.
The first one is about exchange-rate and the display in my console is like this :
{
"exchange_rate": [
{
"id": "978",
"start_dateTime": "2021-08-01 07:35:02",
"target_value": "1.00000",
"currency_value_euro": "0.84097",
"currency_value_dollar_us": "1.00000",
"id_currency": "1",
"currency": "Dollar am\u00e9ricain",
"currency_symbol": "$US"
},
{
"id": "980",
"start_dateTime": "2021-08-01 07:35:02",
"target_value": "1.00000",
"currency_value_euro": "1.17454",
"currency_value_dollar_us": "0.71600",
"id_currency": "2",
"currency": "Livre sterling",
"currency_symbol": "\u00a3"
}
]
}
These data came from the database and I can display it by choosing particular dates with jQuery.
The second array contains only id_currency which in my console is like this : Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5
On my website, I want to be able to display specific exchange rate by specific currency and dates.
And here my problem appears, I can't find the way to loop on the first array, and loop again inside, on the second array and compare both like if first array has id_currency 1 and second array has id_currency 1 then display the complete line from first array.
I've tried several things but nothing works, at last i've tried this :
foreach ($res as $row){
$idBDD = $row['id_currency'];
$symbolBDD = $row['currency_symbol'];
echo $idBDD;
echo $symbolBDD;
//var_dump($row);
/*foreach ($arr as $line){
$idCheckbox = $line;
echo $idCheckbox;
}
if ($idBDD == $idCheckbox){
echo 'fine';
}
*/
}
I'll be grateful for your help
You need to access the array with $res["exchange_rate"] and loop through it then.
<?php
$res = [
"exchange_rate" => [
[
"id" => "978",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value" => "1.00000",
"currency_value_euro" => "0.84097",
"currency_value_dollar_us" => "1.00000",
"id_currency" => "1",
"currency" => "Dollar américain",
"currency_symbol" => "\$US"
],
[
"id" => "980",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value" => "1.00000",
"currency_value_euro" => "1.17454",
"currency_value_dollar_us" => "0.71600",
"id_currency" => "2",
"currency" => "Livre sterling",
"currency_symbol" => "£"
]
]
];
$output = null;
foreach ($res["exchange_rate"] as $row) {
if (!isset($output)) {
$output = $row;
}
$output = array_intersect_assoc($output, $row);
}
var_dump($output);
I think you could do it like this, of course if you're inside the loop, you won't need to put indices.
read more array_diff()
https://www.php.net/manual/pt_BR/function.array-diff.php
$array = [
"exchange_rate" => [
[
"id" => "978",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value"=> "1.00000",
"currency_value_euro"=> "0.84097",
"currency_value_dollar_us"=> "1.00000",
"id_currency"=> "1",
"currency"=> "Dollar am\u00e9ricain",
"currency_symbol" => "US"
],[
"id"=> "980",
"start_dateTime"=> "2021-08-01 07=> 35=> 02",
"target_value"=> "1.00000",
"currency_value_euro"=> "1.17454",
"currency_value_dollar_us"=> "0.71600",
"id_currency"=> "2",
"currency"=> "Livre sterling",
"currency_symbol"=> "\u00a3"
]
]
];
$array1 = $array['exchange_rate'][0];
$array2 = $array['exchange_rate'][1];
$result = array_diff( $array1, $array2);
var_dump($result);

How to remove array of object in PHP

<?php
$test = '{
"100": {
"name": "Sports",
"contentID": "100"
},
"200": {
"name": "Village",
"contentID": "200"
}
}';
$idWiseData = json_decode($test,true);
$test2 = '[
{
"contentID": "100",
"contentStatus": "active"
},
{
"contentID": "200",
"contentStatus": "active"
},
{
"contentID": "300",
"contentStatus": "active"
}
]';
$allTopics = json_decode($test2,true);
foreach ($allTopics as $key => &$topic) {
$contentInfo = [
'contentStatus' => $topic['contentStatus']
];
$topic['contentName'] = isset($idWiseData[$topic['contentID']]['name']) ? $idWiseData[$topic['contentID']]['name'] : null;
}
echo "<pre>";
print_r($allTopics);
?>
Above code is working fine, i am not getting my expected output. actually $allTopics having 3 objects (contentID 100 & 200 & 300).$idWiseData having object (contentID 100 & 200).
I want to take name value from $idWiseData and replace to $allTopics based on contentID.
contentID 300 don't have name so should not come this object.
Expected out put
Array
(
[0] => Array
(
[contentID] => 100
[contentStatus] => active
[contentName] => Sports
)
[1] => Array
(
[contentID] => 200
[contentStatus] => active
[contentName] => Village
)
)
I am getting output
Array
(
[0] => Array
(
[contentID] => 100
[contentStatus] => active
[contentName] => Sports
)
[1] => Array
(
[contentID] => 200
[contentStatus] => active
[contentName] => Village
)
[2] => Array
(
[contentID] => 300
[contentStatus] => active
[contentName] =>
)
)
Kindly anyone update my code please.
As far as I understand you, you need to unset() the index within the array if contentName is null. This can be achieved by using unset()
foreach ($allTopics as $key => &$topic) {
// your code here ....
if (is_null($topic['contentName'])) {
unset(allTopics[$key]);
}
}
You can remove a record from the array by using array_slice. But I would recommend you to change your code and have a 3rd array which must be your result, so then you don't need to change any of your source data.
You're not deleting the index from the array just setting contentName to null. Use unset to delete the index from the array.
Try this one:
<?php
$test = '{
"100": {
"name": "Sports",
"contentID": "100"
},
"200": {
"name": "Village",
"contentID": "200"
}
}';
$idWiseData = json_decode($test,true);
$test2 = '[
{
"contentID": "100",
"contentStatus": "active"
},
{
"contentID": "200",
"contentStatus": "active"
},
{
"contentID": "300",
"contentStatus": "active"
}
]';
$allTopics = json_decode($test2,true);
foreach ($allTopics as $key => &$topic) {
$contentInfo = [
'contentStatus' => $topic['contentStatus']
];
if(isset($idWiseData[$topic['contentID']]['name'])){
$topic['contentName'] = $idWiseData[$topic['contentID']]['name'];
} else {
unset($allTopics[$key]);
}
}
echo "<pre>";
print_r($allTopics);
?>
foreach ($allTopics as $key => &$topic) {
$contentInfo = [
'contentStatus' => $topic['contentStatus']
];
$topic['contentName'] = isset($idWiseData[$topic['contentID']]['name']) ? $idWiseData[$topic['contentID']]['name'] : null;
if (is_null($topic['contentName'])) {
unset($topic['contentName']);
}
}
USE THIS CODE THIS MIGHT SOLVE YOUR PROBLEM.

foreach use value from object twice

I recieve json objects like the following over an rest-service
[
{
"pos_time": "04.09.2018 09:57:02",
"receivetime": "04.09.2018 09:57:18",
"latitude": 47554898,
"longitude": 13173448,
"speed": 8,
"course": 359,
"country": "AT"
},
{
"pos_time": "04.09.2018 09:58:02",
"receivetime": "04.09.2018 09:58:31",
"latitude": 47835502,
"longitude": 13653503,
"speed": 7,
"course": 174,
"country": "AT"
},
]
form this json I want to create a geojson "linestring".
The "linestring" is not the problem. the problem is, that I have to use both coordinates of each object to create the "linestring"
and I have no idea how to loop through the objects and use the coordinates from the second object and first object to create the "linestring"
the result should look like this:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"pos_time": "04.09.2018 09:56:22",
"receivetime": "04.09.2018 09:57:18",
"course": 177,
"speed": 2,
"country": "AT",
"error": null
},
"geometry": {
"type": "LineString",
"coordinates": [
[
13.173448, // object 1
47.554898 // object 1
],
[
13.653503, // object 2
47.835502 // object 2
]
]
}
}
]
}
and the code for the moment looks like this:
// create geojson
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
///////
foreach ($tomtom_request_array as $key => $value) {
if (empty($value['longitude']) || empty($value['latitude']))
{
$longitude = "13.07202";
$latitude = "47.889486";
$error = "Missing or incorrect GPS data";
}
else
{
$latitude = $value['longitude']; // object 1
$longitude = $value['latitude']; // object 1
$latitude_previous = $value['longitude']; // object 2
$longitude_previous = $value['latitude']; // object 2
$error = NULL;
}
if (empty($value['speed']))
{
$speed = "0";
}
else
{
$speed = $value['speed'];
}
if (empty($value['course']))
{
$course = "0";
}
else
{
$course = $value['course'];
}
$feature = array(
'type' => 'Feature',
'properties' => array(
'pos_time' => $value['pos_time'],
'receivetime' => $value['receivetime'],
'course' => $course,
'speed' => $speed,
'country' => $value['country'],
'error' => $error
),
'geometry' => array(
'type' => 'LineString',
'coordinates' => array(
array(($latitude * 0.000001), ($longitude* 0.000001)),
array(($latitude_previous * 0.000001), ($longitude_previous* 0.000001))
),
),
);
array_push($geojson['features'], $feature);
}
$this->response($geojson, $response_status);
}
thanks in advance!
if your Json response is really as you said so it is elementary my dear.You just need to use respective index to retrieve the desired data:
example:
given your JSON response you can proceed like this:
$tomtom_request_array=json_decode('[
{
"pos_time": "04.09.2018 09:57:02",
"receivetime": "04.09.2018 09:57:18",
"latitude": 47554898,
"longitude": 13173448,
"speed": 8,
"course": 359,
"country": "AT"
},
{
"pos_time": "04.09.2018 09:58:02",
"receivetime": "04.09.2018 09:58:31",
"latitude": 47835502,
"longitude": 13653503,
"speed": 7,
"course": 174,
"country": "AT"
}
]',true) ;
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
///////
foreach ($tomtom_request_array as $key => $value) {
if (empty($value['longitude']) || empty($value['latitude']))
{
$longitude = "13.07202";
$latitude = "47.889486";
$error = "Missing or incorrect GPS data";
}
else
{
$latitude = $tomtom_request_array[0]['longitude']; // object 1
$longitude = $tomtom_request_array[0]['latitude']; // object 1
$latitude_previous =$tomtom_request_array[1]['longitude']; // object 2
$longitude_previous =$tomtom_request_array[1]['latitude']; // object 2
$error = NULL;
}
if (empty($value['speed']))
{
$speed = "0";
}
else
{
$speed = $value['speed'];
}
if (empty($value['course']))
{
$course = "0";
}
else
{
$course = $value['course'];
}
$feature = array(
'type' => 'Feature',
'properties' => array(
'pos_time' => $value['pos_time'],
'receivetime' => $value['receivetime'],
'course' => $course,
'speed' => $speed,
'country' => $value['country'],
'error' => $error
),
'geometry' => array(
'type' => 'LineString',
'coordinates' => array(
array(($latitude * 0.000001), ($longitude* 0.000001)),
array(($latitude_previous * 0.000001), ($longitude_previous* 0.000001))
),
),
);
array_push($geojson['features'], $feature);
}
At this step $geojson contains :
print_r($geojson);
Array
(
[type] => FeatureCollection
[features] => Array
(
[0] => Array
(
[type] => Feature
[properties] => Array
(
[pos_time] => 04.09.2018 09:57:02
[receivetime] => 04.09.2018 09:57:18
[course] => 359
[speed] => 8
[country] => AT
[error] =>
)
[geometry] => Array
(
[type] => LineString
[coordinates] => Array
(
[0] => Array
(
[0] => 13.173448
[1] => 47.554898
)
[1] => Array
(
[0] => 13.653503
[1] => 47.835502
)
)
)
)
[1] => Array
(
[type] => Feature
[properties] => Array
(
[pos_time] => 04.09.2018 09:58:02
[receivetime] => 04.09.2018 09:58:31
[course] => 174
[speed] => 7
[country] => AT
[error] =>
)
[geometry] => Array
(
[type] => LineString
[coordinates] => Array
(
[0] => Array
(
[0] => 13.173448
[1] => 47.554898
)
[1] => Array
(
[0] => 13.653503
[1] => 47.835502
)
)
)
)
)
)

Categories