foreach use value from object twice - php

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
)
)
)
)
)
)

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! :)

Transpose subarray data from indexed to associative

I'm making an API for getting some data. My API gives object data like given, given object I wanted to format some data inside object:
{
"data": [
{
"productId": 55,
"productTitle": "Test product",
"variation": {
"Color": "Red",
"Size": "XS",
"din": "10190537",
"product_id": 55,
"name": [
"Color",
"Size"
],
"value": [
"Red",
"XS"
]
},
"din": "10190537",
"markets": [
{
"id": 11,
"name": "paytmmall",
"displayName": "PayTm Mall",
"identifierName": "Product_Id"
}
]
}
]
}
In this object I want data like given
{
"data": [
{
"productId": 55,
"productTitle": "this is test from hariom",
"variation": {
"Color": "Red",
"Size": "XS",
"din": "10190537",
"product_id": 55,
"variationTypes": [
{
"name": "Color",
"value": "Red"
},
{
"name": "Size",
"value": "XS"
}
],
},
"din": "10190537",
"markets": [
{
"id": 11,
"name": "paytmmall",
"displayName": "PayTm Mall",
"identifierName": "Product_Id"
}
]
}
]
}
Here Is my Controller Name
public function MarketMapping(Request $request)
{
$sellerId = Auth::guard('seller-api')->user();
$page = $request->has('pageNumber') ? $request->get('pageNumber') : 1;
$limit = $request->has('perPage') ? $request->get('perPage') : 10;
$variationFromInvTbl = ProductInventory::select('Color', 'Size', 'din', 'product_id')->where('seller_id', $sellerId->id)->where('status', 'active')->limit($limit)->offset(($page - 1) * $limit)->get();
$dataArray = array();
foreach($variationFromInvTbl as $key => $varitionValue)
{
$prodtsFromLivetbl = ProductsLive::select('productTitle', 'product_id')->where('product_id', $varitionValue->product_id)->get();
foreach ($prodtsFromLivetbl as $key => $value)
{
$marketChannelData = DB::table('market_channels')
->join('sellers_market_channels', 'market_channels.name', '=', 'sellers_market_channels.key')
//->join('market_product_mappings', 'market_channels.id', '=', 'market_product_mappings.market_id')
->select('market_channels.id','market_channels.name', 'market_channels.displayName','market_channels.identifierName') //'market_product_mappings.identifierValue'
->where('sellers_market_channels.seller_id', $sellerId->id)
->where('sellers_market_channels.value', 1)
->get();
$maketProductMap = MarketProductMapping::where('seller_id', $sellerId->id)->where('product_id', $varitionValue->product_id)->where('din', $varitionValue->din)->pluck('identifierValue');
if (count($maketProductMap))
{
$marketChannelData[$key]->value = $maketProductMap[0];
}
$varitionValue['name']= array_keys($varitionValue->only(['Color', 'Size']));
$varitionValue['value'] = array_values($varitionValue->only(['Color', 'Size']));
$dataObject = ((object)[
"productId" => $value->product_id,
"productTitle" => $value->productTitle,
"variation" => $varitionValue,
"din" => $varitionValue['din'],
"markets" => $marketChannelData
]);
array_push($dataArray,$dataObject);
}
}
if($variationFromInvTbl)
{
$response['success'] = true;
$response["page"] = $page;
$response["itemPerPage"] = $limit;
$response["totalRecords"] = $this->CountMarketMapping($page, $limit, $sellerId->id);
$response['data'] = $dataArray;
return response()->json($response, 200);
}else{
$response['success'] = false;
$response['data'] = $prodtsFromLivetbl;
return response()->json($response, 409);
}
}
You are using laravel's only() method which returns an associative array.
You wish to convert each key-value pair into a subarray containing two associative elements -- the original key will be the value of the name element
and the original value will be the value of the value element.
By passing the original array keys and array values into array_map(), you can iterate them both synchronously.
compact() is a perfect native function to create the desired associative subarrays from the iterated parameters.
Code: (Demo)
$variations = $varitionValue->only(['Color', 'Size']);
$dataObject = (object)[
// ... your other data
'variations' => array_map(
function($name, $value) {
return compact(['name', 'value']);
},
array_keys($variations),
$variations
),
// ...your other data
];
var_export($dataObject);
Output:
(object) array(
'variations' =>
array (
0 =>
array (
'name' => 'Color',
'value' => 'Red',
),
1 =>
array (
'name' => 'Size',
'value' => 'XS',
),
),
)
This script will help you
<?php
$data = [
"variation" => [
[
"Color" => "Red",
"Size" => "XS",
"din" => "10190537",
"product_id" => 55,
"name" => [
"0" => "Color",
"1" => "Size"
],
"value" => [
"0" => "Red",
"1" => "XS"
]
]
]
];
for ($i=0; $i < count($data["variation"]); $i++) {
$data["variation"][$i]["data"]["name"] = $data["variation"][$i]["name"];
$data["variation"][$i]["data"]["value"] = $data["variation"][$i]["value"];
unset($data["variation"][$i]["name"]);
unset($data["variation"][$i]["value"]);
}
print_r($data);
output
Array
(
[variation] => Array
(
[0] => Array
(
[Color] => Red
[Size] => XS
[din] => 10190537
[product_id] => 55
[data] => Array
(
[name] => Array
(
[0] => Color
[1] => Size
)
[value] => Array
(
[0] => Red
[1] => XS
)
)
)
)
)

PHP: Accessing data within complex json

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 .

Use array_filter on multi dimensional array

I'm trying to filter an array that looks like this
$array = array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array(
"otherID" => "theValueIamLookingFor",
"someOtherKey" => "something"
)
);
Now, I'm filtering for data sets, where "otherID" is a certain value. I know I could use array_filter to filter for "id", but I can't for the life of me figure out how to filter for a value in an array inside an array.
Adding some of the data as provided by the WebAPI (I run that through json_decode to create an associative array before all this filtering business)
[
{
"id": "b679d716-7cfa-42c4-9394-3abcdged",
"name": "someName",
"actualCloseDate": "9999-12-31T00:00:00+01:00",
"members": [
{
"otherID": "31f27f9e-abcd-1234-aslkdhkj2j4",
"name": "someCompany"
}
],
"competitor": null,
},
{
"id": "c315471f-45678-4as45-457-asli74hjkl",
"name": "someName",
"actualCloseDate": "9999-12-31T00:00:00+01:00",
"members": [
{
"otherID": "askgfas-agskf-as",
"name": "someName"
}
],
"competitor": null,
},
]
You can do something like:
$arr = array(
array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array (
"otherID" => "ThisIsNottheValueIamLookingFor",
"someOtherKey" => "something"
)
),
array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array (
"otherID" => "theValueIamLookingFor",
"someOtherKey" => "something"
)
),
array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array (
"otherID" => "ThisIsNottheValueIamLookingForEither",
"someOtherKey" => "something"
)
),
);
$result = array_filter($arr, function( $v ){
return $v["Members"]["otherID"] == "theValueIamLookingFor";
});
This will result to:
Array
(
[1] => Array
(
[id] => SomeID
[name] => SomeName
[Members] => Array
(
[otherID] => theValueIamLookingFor
[someOtherKey] => something
)
)
)
Here is the doc for more info: http://php.net/manual/en/function.array-filter.php
UPDATE
On you Updated array, the structure of array is different. You have to use $v["members"][0]["otherID"] to get the otherID
Please try the code below:
$result = array_filter($arr, function( $v ){
return $v["members"][0]["otherID"] == "theValueIamLookingFor";
});

Categories