I have created an array to convert into json file in php. But as per the requirement I need to assign an array to this array element. it's an array inside an array.
"data" => array( // data array
array(
"event_name" => "Purchase",
"event_time" => time(),
"event_id" => $order_id,
"user_data" => array(
"client_ip_address" => $ip,
"client_user_agent" => $browser,
"em" => $email,
"ph" => $phone,
"fbc" =>$fbp,
"fbp" =>$fbc,
"fn" => $fn,
"ct" => $ct,
"st" => $st,
"zp" => $zp,
"country" => $country,
"external_id" => $email
),
"contents" => $items,
// "id" => $item_ids,
// "quantity" => count($item_qty),
// // "delivery_category"=> "home_delivery",
// "order_id" => $order_id
// ),
"custom_data" => array(
"currency" => "GBP",
"value" => $order_total,
),
"action_source" => "website",
"event_source_url" => $fullURL,
),
)
);
But my $item array look like this when I echo
{
"id": 814,
"order_id": 36956,
"name": "Pearson BTEC Level 7 Certificate in Strategic Management and Leadership (RQF)",
"product_id": 19555,
"variation_id": 0,
"quantity": 2,
"tax_class": "",
"subtotal": "1158",
"subtotal_tax": "0",
"total": "1158",
"total_tax": "0",
"taxes": {
"total": [],
"subtotal": []
},
"meta_data": []
},
{
"id": 815,
"order_id": 36956,
"name": "Pearson BTEC Level 7 Diploma in Strategic Management and Leadership (RQF)",
"product_id": 19107,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "999",
"subtotal_tax": "0",
"total": "999",
"total_tax": "0",
"taxes": {
"total": [],
"subtotal": []
},
"meta_data": []
}
And when I assign this $items and converted to json then I can see only the ides of the array
"user_data": {
"client_ip_address": "2402:d000:a200:a4a8:f06d:40a:cf85:e26d",
"client_user_agent": "",
"em": "b99526fedef7fe1da29e27d6f09cb64efew536978778e6cde3d8277d71a04398d1a4",
"ph": "db80005a39b11372054b7708cac76gsaaww47af6ed3fe4b37b9a8b2be435e2fcff04a7",
"fbc": "",
"fbp": "",
"fn": "83cd072a16ddb3d793c2f5bcd7d0basdree5a04af680279cf6a26fb8dffe57ce3b51a",
"ct": "17a0730b80e55f4bee9569be3f7e6d0wqw500c5568ecb8d785759d7151ef40f5bbd",
"st": "e3b0c44298fc1c149afbf4c8996fb9sas2427ae41e4649b934ca495991b7852b855",
"zp": "ac7bb74de6884ffce919c15fef4193749sdsd4588026c643973946713ac46da540d",
"country": "c820736841e811c96d30b14eb998feb6bsddc2c9d0764b7731267438dc7d6bb5b59",
"external_id": "b99526fedef7fe1da29e27d6f09ssscb64536978778e6cde3d8277d71a04398d1a4"
},
"contents": [
{
"814": {},
"815": {}
}
],
result should be look like this in this way in "centents" element
"contents" : [{'id':'ABC123','quantity' :2,'item_price':5.99}, {'id':'XYZ789','quantity':2, 'item_price':9.99, 'delivery_category': 'in_store'}]
I think the problem is that your $items, is actually an array of "strings" (json)
try to do a json_decode() on those $items before adding it to the content.
anyway, when you ask a question try to remove all unnecessary stuff, and make an example with the minimum code you need help with, in this case it takes a lot of reading through stuff just to understand the issue.
Related
This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How can I replace a specific key's value in an array in php?
(2 answers)
Closed 7 months ago.
I all, I've been staring at this for hours so any help is greatly appreciated. I have an array...
$aircraft = [
'N7826C' => ['nnum' => 'N7826C', 'name' => 'ANAHEIM POLICE DEPT', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N226PD' => ['nnum' => 'N226PD', 'name' => 'ANAHEIM POLICE DEPT', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N326PD' => ['nnum' => 'N326PD', 'name' => 'CITY OF ANAHEIM', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N826PD' => ['nnum' => 'N826PD', 'name' => 'CITY OF ANAHEIM', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0']
];
With that array, I implode it to get a list of the nnums to pass through a API....
$aircraftNNUMlist = implode(',', array_map(function($v) { return $v['nnum']; }, $aircraft));
$json = file_get_contents('https://airlabs.co/api/v9/flights?_fields=reg_number,lat,lng®_number='.$aircraftNNUMlist.'&api_key=XXXXX');
That API returns...
{
"request": {
"lang": "en",
"currency": "USD",
"time": 15,
"id": "c9by9lmq1q0",
"server": "z",
"host": "airlabs.co",
"pid": 322387,
"key": {
"id": 19146,
"api_key": "xxxxxxxxxxxxxxxx",
"type": "free",
"expired": "2022-08-20T22:00:00.000Z",
"registered": "2022-07-19T03:51:04.000Z",
"limits_by_hour": 2500,
"limits_by_minute": 250,
"limits_by_month": 1000,
"limits_total": 628
},
"params": {
"_fields": "reg_number,lat,lng",
"reg_number": "N60NT,N40NT,N30NT,N10NT",
"lang": "en"
},
"version": 9,
"method": "flights",
"client": {
"ip": "xxxxxxxxxxxxxxxxx",
"geo": {
"country_code": "US",
"country": "United States",
"continent": "North America",
"city": "Provo",
"lat": 40.2181,
"lng": -111.6133,
"timezone": "America/Denver"
},
"connection": {
"type": "corporate",
"isp_code": 46606,
"isp_name": "Unified Layer"
},
"device": {},
"agent": {},
"karma": {
"is_blocked": false,
"is_crawler": false,
"is_bot": false,
"is_friend": false,
"is_regular": true
}
}
},
"response": [
{
"reg_number": "N60NT",
"lat": 34.11,
"lng": -117.69
}
],
"terms": "Unauthorized access is prohibited and punishable by law. \nReselling data 'As Is' without AirLabs.Co permission is strictly prohibited. \nFull terms on https://airlabs.co/. \nContact us info#airlabs.co"
}
I am having trouble looping through the "response" of the API return (stored at $json) to update the corresponding index in $aircraft. If a nnum isn't currently active there will not be a entry in "response" for instance "response" only has N60NT in the return array. I am fairly new to arrays so I've been taking swings in the dark and nothing seems to be right.
I presume you have json_decoded your api json response into a PHP array. Well actually:
$arr = json_decode($json_form_api, true);
$response = $arr["response"];
foreach ($response as $sub) {
$reg = $sub["reg_number"];
$aircraft[$reg]["lat"] = $sub["lat"];
$aircraft[$reg]["lng"] = $sub["lng"];
}
I am using sports-radar API to get the schedule of NFL week 1. The API returns the following data in json format (I shortened string for example).
"id": "8e45fe2d-fb95-4504-845d-7c815623ccd6",
"year": 2018,
"type": "REG",
"name": "REG",
"week": {
"id": "37435167-5cf6-4cce-b405-ff0e264ced9c",
"sequence": 1,
"title": "1",
"games": [{
"id": "0822b924-eadc-4398-bfe6-83cbbf3a2912",
"status": "scheduled",
"reference": "57570",
"number": 4,
"scheduled": "2018-09-09T17:00:00+00:00",
"entry_mode": "INGEST",
"venue": {
"id": "6ed18563-53e0-46c2-a91d-12d73a16456d",
"name": "Lucas Oil Stadium",
"city": "Indianapolis",
"state": "IN",
"country": "USA",
"zip": "46225",
"address": "500 South Capitol Avenue",
"capacity": 67000,
"surface": "artificial",
"roof_type": "retractable_dome"
},
"home": {
"id": "82cf9565-6eb9-4f01-bdbd-5aa0d472fcd9",
"name": "Indianapolis Colts",
"alias": "IND",
"game_number": 1
},
"away": {
"id": "ad4ae08f-d808-42d5-a1e6-e9bc4e34d123",
"name": "Cincinnati Bengals",
"alias": "CIN",
"game_number": 1
},
"broadcast": {
"network": "CBS"
}
}, {
"id": "0a456149-c547-4856-9b1b-86e1d93887ae",
"status": "scheduled",
"reference": "57574",
"number": 8,
"scheduled": "2018-09-09T17:00:00+00:00",
"entry_mode": "INGEST",
"venue": {
"id": "3c85d89a-ec66-4983-acd5-1381d6c8673a",
"name": "Mercedes-Benz Superdome",
"city": "New Orleans",
"state": "LA",
"country": "USA",
"zip": "70112",
"address": "1500 Sugar Bowl Drive",
"capacity": 73208,
"surface": "artificial",
"roof_type": "dome"
},
"home": {
"id": "0d855753-ea21-4953-89f9-0e20aff9eb73",
"name": "New Orleans Saints",
"alias": "NO",
"game_number": 1
},
"away": {
"id": "4254d319-1bc7-4f81-b4ab-b5e6f3402b69",
"name": "Tampa Bay Buccaneers",
"alias": "TB",
"game_number": 1
},
"broadcast": {
"network": "FOX"
I used the following website as a tutorial on how to display only the the data I need and how to loop over it
Note the JSON string is stored in the variable $schedule
MY Code
// JSON string
$jsonData = $schedule; //get json string
// Convert JSON string to Array
$jsonArray = json_decode($jsonData, true);
// Convert JSON string to Object
$jsonObject = json_decode($schedule);
Looping through PHP Array or Object
$someArray = $jsonArray
foreach ($someArray as $key => $value) {
echo $value["home"] . ", " . $value["away"] . "<br>";
}
// Loop through Object
$someObject = jsonObject
foreach($someObject as $key => $value) {
echo $value->home . ", " . $value->away . "<br>";
}
My ERRORS
When trying to convert the string to an array and attempting to get the away team name I get the error Illegal string offset 'away' same problem with home and all other data
When trying to access data as an object I get the following error Trying to get property of non-object
I followed the tutorial to the letter. Yet im getting the basic errors above...? Any help and explanation would be appreciated. Thank you
EDIT:
var_export($schedule) returns the following:
array ( 'id' => '8e45fe2d-fb95-4504-845d-7c815623ccd6', 'year' => 2018, 'type' => 'REG', 'name' => 'REG', 'week' => array ( 'id' => '37435167-5cf6-4cce-b405-ff0e264ced9c', 'sequence' => 1, 'title' => '1', 'games' => array ( 0 => array ( 'id' => '0822b924-eadc-4398-bfe6-83cbbf3a2912', 'status' => 'scheduled', 'reference' => '57570', 'number' => 4, 'scheduled' => '2018-09-09T17:00:00+00:00', 'entry_mode' => 'INGEST', 'venue' => array ( 'id' => '6ed18563-53e0-46c2-a91d-12d73a16456d', 'name' => 'Lucas Oil Stadium', 'city' => 'Indianapolis', 'state' => 'IN', 'country' => 'USA', 'zip' => '46225', 'address' => '500 South Capitol Avenue', 'capacity' => 67000, 'surface' => 'artificial', 'roof_type' => 'retractable_dome', ), 'home' => array ( 'id' => '82cf9565-6eb9-4f01-bdbd-5aa0d472fcd9', 'name' => 'Indianapolis Colts', 'alias' => 'IND', 'game_number' => 1, ),
You are dealing with array of arrays. Try something like this:
$someArray = $jsonArray
foreach ($someArray as $key => $value) {
echo $value["home"]["name"] . ", " . $value["away"]["name"] . "<br>";
}
I am using laravel 5.5 API resource collection for showing list of products. I am using an array instead of the modal object. I got my list of items but i am not sure how to show item variant array in the response. The actual response array passing to the api resource are:
{
"ID": 3160,
"UserID": 3302,
"ItemName": "2",
"Description": "2",
"Price": 2,
"StockLimited": true,
"StockQuantity": 19,
"CurrencyCode": "USD",
"ImageUrl": "/images/items/Item3302-636434761494584365-qq5HFm.png",
"VariantItems": [
{
"ID": 3181,
"ItemName": "2",
"Price": 0,
"StockLimited": false,
"StockQuantity": 0,
"CurrencyCode": "USD",
"Variants": [
{
"Id": 1099,
"Name": "Red",
"VariantGroupId": 1027,
"VariantGroupName": "Colour"
},
{
"Id": 1111,
"Name": "S",
"VariantGroupId": 1028,
"VariantGroupName": "Size"
}
]
},
{
"ID": 3182,
"ItemName": "2",
"Price": 0,
"StockLimited": false,
"StockQuantity": 0,
"CurrencyCode": "USD",
"Variants": [
{
"Id": 1099,
"Name": "Red",
"VariantGroupId": 1027,
"VariantGroupName": "Colour"
},
{
"Id": 1112,
"Name": "M",
"VariantGroupId": 1028,
"VariantGroupName": "Size"
}
]
}
],
"MerchantName": "seller",
"VariantGroupLists": [
{
"VariantGroupName": "Colour",
"Names": [
"Red",
"Grey",
"Navy"
]
},
{
"VariantGroupName": "Size",
"Names": [
"S",
"M",
"L",
"XL"
]
}
]
}
My ItemResourceCollection
public function toArray($request)
{
return [
'data' => $this->collection->map(function ($item) use ($request) {
return (new ItemResource($item))->toArray($request);
})
];
}
My ItemResource
public function toArray($request)
{
return [
"item_id" => $this->resource->ID,
"item_name" => $this->resource->ItemName,
"description" =>$this->resource->Description,
"item_price"=>$this->resource->Price,
"stock_qty"=>$this->resource->StockQuantity,
"currency_code"=>$this->resource->CurrencyCode,
"item_image_url"=>$this->resource->ImageUrl,
];
}
public function with($request)
{
return ['item_varients' => [new ItemResource($this->resource->VariantItems)]];
}
What I am trying to achieve is this result:
[
{
"item_id": 3160,
"item_name": "BLACK COWL NECK DRESS WITH DIAMANTE DETAIL",
"description": "Test test",
"item_price": 16.99,
"stock_qty": 20,
"currency_code": "SGD",
"item_image_url": "/images/items/Item18-636231488325192562-GoiIBl.png",
"item_varients": [
{
"id": 29,
"name": "Red",
"varientgroupId": 11,
"varientgroupname": "Color"
}
]
}
]
the with() method in ItemResource is not working. How do I add the "item_varients" array in the resource response?
I would first move the line to add the item_varients property inside the method toArray like following:
public function toArray($request)
{
return [
"item_id" => $this->resource->ID,
"item_name" => $this->resource->ItemName,
"description" => $this->resource->Description,
"item_price" => $this->resource->Price,
"stock_qty" => $this->resource->StockQuantity,
"currency_code" => $this->resource->CurrencyCode,
"item_image_url" => $this->resource->ImageUrl,
"item_varients" => [
new ItemResource($this->resource->VariantItems)
]
]
}
Meta information
We do that because the with is meant for to add a meta information block or something similar. See https://laravel.com/docs/5.5/eloquent-resources#adding-meta-data
The advantage when using the with method is, that multiple resources results in only one meta block. This is not what you want, I think.
Resource for VariantItem
I think you have to build a Resource class also for VariantItem. And because the VariantItems are a collection you also have to fill your array called item_variants similar to your ItemResourceCollection. So change your code to look like this:
public function toArray($request)
{
/**
* Prepare your variant items to have a collection
*
* #var Collection $variantItems
*/
$variantItems = collect($this->resource->VariantItems);
return [
"item_id" => $this->resource->ID,
"item_name" => $this->resource->ItemName,
"description" => $this->resource->Description,
"item_price" => $this->resource->Price,
"stock_qty" > $this->resource->StockQuantity,
"currency_code" => $this->resource->CurrencyCode,
"item_image_url" => $this->resource->ImageUrl,
"item_varients" => VariantItem::collection($variantItems)
]
}
Here is the best way to get specific fields using a collection
return [
'id' => $this->id,
'variant_item' => new CustomResource($this->user, ['item_id', 'item_name', 'item_size'])
];
I have been trying to solve my problem for days, but without getting the desidred result. Here's a particular structure for a JSON file:
{
"detections": {
"timestamp": "12/04/2016/ 20:25:00",
"rooms": [
{
"name": "r1",
"sensors": [
{
"id": 10,
"type": "rad",
"value": 100,
"valMax": 600,
"valMin": 100
},
{
"id": 12,
"type": "temp",
"value": 30.5,
"valMax": 1000,
"valMin": 0
}
]
},
{
"name": "r2",
"sensors": [
{
"id": 20,
"type": "temp",
"value": 20.7,
"valMax": 1000,
"valMin": 0
},
{
"id": 15,
"type": "rad",
"value": 800,
"valMax": 600,
"valMin": 100
}
]
}
]
}
}
I must encode with that structure data that I've retrieved from MySQL Database.
It consists of three tables linked with foreign key constraints. Now, the code I've written for this is the following:
while($row = mysqli_fetch_array($result)) {
array_push($detections, array("timestamp"=>$row['timestamp'],
"rooms"=>array("name"=>$row['name'],
"sensors"=>array("id"=>$row['id'], "type"=>$row['type'], "value"=>$row['value'], "valMin"=>$row['valMin'],
"valMax"=>$row['valMax']))
));
}
But it gives me this result:
{
"detections": [{
"timestamp": "2016-09-10 17:59:06",
"rooms": {
"name": "Stanza dei Giochi",
"sensors": {
"id": "1",
"type": "prova2",
"value": "12",
"valMin": "1",
"valMax": "12"
}
}
}, {
"timestamp": "2016-09-11 00:41:21",
"rooms": {
"name": "Stanza dei Giochi",
"sensors": {
"id": "1",
"type": "prova2",
"value": "21",
"valMin": "1",
"valMax": "12"
}
}
}, {
"timestamp": "2016-09-10 19:59:20",
"rooms": {
"name": "Stanza dei Giochi",
"sensors": {
"id": "3",
"type": "prova",
"value": "13",
"valMin": "11",
"valMax": "13"
}
}
}, {
"timestamp": "2016-09-11 00:41:21",
"rooms": {
"name": "Stanza dei Giochi",
"sensors": {
"id": "3",
"type": "prova",
"value": "23.5",
"valMin": "11",
"valMax": "13"
}
}
}]
}
which is similar but not the same :/
As I've noticed from the JSON structure I would get, detections with the same timestamp but with different rooms, sensors and values are collected together... but I don't know how to realize that.
Hope y'all can give me a hand, thanks >.<
You are building your array wrong to achieve that structure.
To achieve the desired structure your array needs to look like this
<?php
array (
'detections' =>
array (
'timestamp' => '12/04/2016/ 20:25:00',
'rooms' =>
array (
0 =>
array (
'name' => 'r1',
'sensors' =>
array (
0 =>
array (
'id' => 10,
'type' => 'rad',
'value' => 100,
'valMax' => 600,
'valMin' => 100,
),
1 =>
array (
'id' => 12,
'type' => 'temp',
'value' => 30.5,
'valMax' => 1000,
'valMin' => 0,
),
),
),
1 =>
array (
'name' => 'r2',
'sensors' =>
array (
0 =>
array (
'id' => 20,
'type' => 'temp',
'value' => 20.699999999999999,
'valMax' => 1000,
'valMin' => 0,
),
1 =>
array (
'id' => 15,
'type' => 'rad',
'value' => 800,
'valMax' => 600,
'valMin' => 100,
),
),
),
),
),
);
Check also check json_decode and json_encode
I need to append certain values of Second array to the first array
I.e.,
In the First Array i create two elements such as name and price and get the values from Second Array and give it to first array
Here is my First Array
[
{
"id": 8,
"user_id": 21,
"category_id": 1,
"juice_id": 2,
"count": "100",
"status": "1",
"created_at": "2016-02-23 07:12:14",
"updated_at": "2016-02-23 07:12:14"
},
{
"id": 9,
"user_id": 21,
"category_id": 1,
"juice_id": 1,
"count": "100",
"status": "1",
"created_at": "2016-02-23 07:15:47",
"updated_at": "2016-02-23 07:15:47"
}
]
And the Second array is
{
"1": {
"id": 2,
"store_id": 1,
"category_id": 1,
"name": "Cashew Butter Baby",
"image": "http://greenhoppingbucket.s3.amazonaws.com/juice/1455719144rebV3iRUlj.png",
"description": "Cashew, Butter and Milk",
"price": "12.00",
"status": 1,
"created_at": "2016-02-17 19:56:11",
"updated_at": "2016-02-17 19:56:11"
},
"2": {
"id": 1,
"store_id": 1,
"category_id": 1,
"name": "Kalekolada",
"image": "http://greenhoppingbucket.s3.amazonaws.com/juice/1455719105WAVB3SGxT7.png",
"description": "Pulp of Kale",
"price": "10.00",
"status": 1,
"created_at": "2016-02-17 19:55:34",
"updated_at": "2016-02-17 19:55:34"
}
}
My Expected result is
[
{
"id": 8,
"user_id": 21,
"category_id": 1,
"juice_id": 2,
"count": "100",
"status": "1",
"created_at": "2016-02-23 07:12:14",
"updated_at": "2016-02-23 07:12:14"
"name": "Cashew Butter Baby",
"price": "12.00",
},
{
"id": 9,
"user_id": 21,
"category_id": 1,
"juice_id": 1,
"count": "100",
"status": "1",
"created_at": "2016-02-23 07:15:47",
"updated_at": "2016-02-23 07:15:47",
"name": "Kalekolada",
"price": "10.00",
}
]
I tried to do $newArray = array_merge($cartData, $juiceData);
But it is simply merging two arrays.
What is the mistake and how can i do that ?
Here's some code for merging those arrays. You should have a common index for them though (a different order may lead to unexpected behavior).
<?php
$a = array(
array(
"id" => 8,
"user_id" => 21,
"category_id" => 1,
"juice_id" => 2,
"count" => "100",
"status" => "1",
"created_at" => "2016-02-23 07:12:14",
"updated_at" => "2016-02-23 07:12:14"
),
array(
"id" => 9,
"user_id" => 21,
"category_id" => 1,
"juice_id" => 1,
"count" => "100",
"status" => "1",
"created_at" => "2016-02-23 07:15:47",
"updated_at" => "2016-02-23 07:15:47"
)
);
$b = array(
array(
"id" => 2,
"store_id" => 1,
"category_id" => 1,
"name" => "Cashew Butter Baby",
"image" => "http://greenhoppingbucket.s3.amazonaws.com/juice/1455719144rebV3iRUlj.png",
"description" => "Cashew, Butter and Milk",
"price" => "12.00",
"status" => 1,
"created_at" => "2016-02-17 19:56:11",
"updated_at" => "2016-02-17 19:56:11"
),
array(
"id" => 1,
"store_id" => 1,
"category_id" => 1,
"name" => "Kalekolada",
"image" => "http://greenhoppingbucket.s3.amazonaws.com/juice/1455719105WAVB3SGxT7.png",
"description" => "Pulp of Kale",
"price" => "10.00",
"status" => 1,
"created_at" => "2016-02-17 19:55:34",
"updated_at" => "2016-02-17 19:55:34"
)
);
// For this to work the arrays need to have the same string keys
// $merge = array_merge_recursive( $a, $b );
$merge = array();
foreach( $b as $key => $entry ) {
if( isset($a[$key]) ) {
$entry += $a[$key];
}
$merge[] = $entry;
}
var_dump( $merge );
EDIT:
New info in comments would give us something like:
$categories = array();
foreach( $b as &$entry ) {
$categories[$entry['id']] =& $entry;
}
$products = array();
foreach( $a as &$entry ) {
if( isset($categories[$entry['juice_id']]) ) {
$entry['category'] =& $categories[$entry['juice_id']];
}
$products[] =& $entry;
}
var_dump( $products );
No need to pass them by reference but should save some memory.