How to reproduce with PHP a particular JSON document - php

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

Related

add values ​from a collection to others using a column as a reference (PHP, LARAVEL)

I am working with php in laravel, in this case I have 2 collections of objects, one of them looks like this:
[
{
"id": 1,
"name": "product x",
"quantity": "100",
},
{
"id": 2,
"codProd": "product y",
"quantity": "200",
},
{
"id": 3,
"name": "product a.",
"quantity": "30",
}
]
and the other looks like this:
[
{
"reference": 1,
"quantity": "80",
},
{
"reference": 2,
"quantity": "50",
},
]
What I need is to keep the first collection but adding the value of the quantity key from the second collection, using the reference key as a relationship with the id of the first collection, the final result should look like this:
[
{
"id": 1,
"name": "product x",
"quantity": "180",
},
{
"id": 2,
"codProd": "product y",
"quantity": "250",
},
{
"id": 3,
"name": "product a.",
"quantity": "30",
}
]
so how can I do this?, any guide or help I am grateful
You can use a collection method for this, the map method:
$collection_one = collect([
[
'id' => 1,
'name' => 'product x',
'quantity' => 100,
],
[
'id' => 2,
'name' => 'product y',
'quantity' => 100,
],
[
'id' => 1,
'name' => 'product a.',
'quantity' => 30,
],
]);
$collection_two = collect([
[
'reference' => 1,
'quantity' => 80,
],
[
'reference' => 2,
'quantity' => 50,
],
]);
For you to get the collection what you want:
$collect = [];
$collect = $collection_one->map(function ($value_one) use ($collection_two) {
if ($search = $collection_two->firstWhere('reference', '=', $value_one['id'])) {
$value_one['quantity'] += $search['quantity'];
}
return $value_one;
});
Ready, that worked for me. :)

Need a help to assign array to array element of php

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.

Getting JSON data from API as array or object

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>";
}

How to combine bool must and sort for elasticsearch

i am trying to sort some data, where in my base skeleton my sorting is not working and if i remove the sorting it works fine.
So how can i put sorting in my base skeleton and sort some data.
i can't put just
$params['body'] = [
'sort' => [['title' => ['order' => 'asc']]]];
$results = $client->search($params);
Because i have other condition where i need the must condition.
Can anyone knows how it can be solve.
Any advice will be really appreciate.
// my base skeleton
$params = array(
'index' => "myIndex",
'type' => "myType",
'body' => array(
'query' => array(
'bool' => array(
'must' => array(
// empty should clause for starters
)
)
),
'sort' => array()
)
);
// sorting is not working with bool and must
if ($request->request->get('salarySort')) {
$params['body']['query']['bool']['must'][] = array(
'sort' => array(
"title" => array('order' => 'asc')
)
);
}
this is what i get as a json_encode ---
{
"took": 4,
"timed_out": false,
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"hits": {
"total": 1066,
"max_score": null,
"hits": [
{
"_index": "myIndex",
"_type": "myType",
"_id": "pe065319de73937aa6ef46413afd7aac26a58a611",
"_score": null,
"_source": {
"title": "Smarason trycker ",
"content": "HIF gör 2-0 mot Halmstad.",
"tag": [
"Soprts"
],
"category": [
"Sports"
]
},
"sort": [
"0"
]
},
{
"_index": "myIndex",
"_type": "myType",
"_id": "pebc44a70008f53f74f23ab23f8a1f79b2b729448",
"_score": null,
"_source": {
"title": "Anders Svenssons tips gav 1-0",
"content": "Anders Svenssons tips i halvtid Kalmar FF.",
"source": "Unknown",
"tag": [
"Soprts"
],
"category": [
"Sports"
]
},
"sort": [
"0"
]
}
]
}
}
query in JSON ---
{
"index": "myIndex",
"type": "myType",
"size": 30,
"body": {
"query": {
"match_all": []
},
"sort": [
{
"title": "asc"
}
]
}
}
You're almost there. You've correctly placed the empty sort array at the same level as your query, which is correct.
The issue comes later when you try to feed it as a bool/must constraint instead of in the empty sort array.
// sorting is not working with bool and must
if ($request->request->get('salarySort')) {
$params['body']['sort'][] = array( <---- this line needs to be changed
"Salary" => 'asc' <---- this line needs to be changed, too
);
}

I can not get data to aggregate It. PHP + mongoDB

It works like I need:
$out = $collection->aggregate(
array(
'$match' => array('type' => 'chair')
),
array(
'$project' => array(
'chairtype' => 1,
'mijczjeqeo'=>1
)
),
array(
'$group' => array(
'_id' => '$chairtype',
'MIDDLE_mijczjeqeo' => array('$avg' => '$mijczjeqeo'),
'SUMMA__mijczjeqeo' => array('$sum' => '$mijczjeqeo')
)
)
);
my_dump($out);
But i need to get true data for aggregation from array in the same documents: versions[0][content][mijczjeqeo]
Please correct my script. It does not work:
$out = $collection->aggregate(
array(
'$match' => array('type' => 'chair')
),
array(
'$project' => array(
'chairtype' => 1,
'versions.0.content.mijczjeqeo'=>1
)
),
array(
'$group' => array(
'_id' => '$chairtype',
'MIDDLEmijczjeqeo' => array('$avg' => '$versions.0.content.mijczjeqeo'),
'SUMMAmijczjeqeo' => array('$sum' => '$versions[0]["content"]["mijczjeqeo"]')
)
)
);
no one method does not work:
'MIDDLEmijczjeqeo' => array('$avg' => '$versions.0.content.mijczjeqeo')
'SUMMAmijczjeqeo' => array('$sum' => '$versions[0]["content"]["mijczjeqeo"]')
I think the problem near .0.
I try to do it in mongo console...
db.documents.aggregate({$match:{'type':'chair'}},{$project:{'chairtype': 1, 'mijczjeqeo':1}},{$group:{'_id':'$chairtype','MID':{$avg:'$mijczjeqeo'}}})
{
"result" : [
{
"_id" : "T",
"MID" : 6.615384615384615
},
{
"_id" : "G",
"MID" : 8.310344827586206
},
{
"_id" : "E",
"MID" : 6.9523809523809526
}
],
"ok" : 1
}
db.documents.aggregate({$match:{'type':'chair'}},{$project:{'chairtype': 1, 'versions.0.content.mijczjeqeo':1}},{$group:{'_id':'$chairtype','MID':{$avg:'$versions.0.content.mijczjeqeo'}}})
{
"result" : [
{
"_id" : "T",
"MID" : 0
},
{
"_id" : "G",
"MID" : 0
},
{
"_id" : "E",
"MID" : 0
}
],
"ok" : 1
}
Well you cannot project like that in the aggregation pipeline. If you want to act on array elements within an aggregation statement you first need to $unwind the array and then either $match the required element(s) or as in your case choose the $first item using an additional $group stage.
Your question does not show the structure of a document so I'll just use a sample, as my "chairs" collection:
{
"_id": 1,
"type": "chair",
"chairtype": "A",
"versions": [
{
"revision": 1,
"content": {
"name": "ABC",
"value": 10
}
},
{
"revision": 2,
"content": {
"name": "BBB",
"value": 15
}
}
]
}
{
"_id": 2,
"type": "chair",
"chairtype": "A",
"versions": [
{
"revision": 1,
"content": {
"name": "CCC",
"value": 20
}
},
{
"revision": 2,
"content": {
"name": "BAB",
"value": 12
}
}
]
}
Minimal, but enough to get the point. Now the aggregate statement:
db.chairs.aggregate([
// Normal query matching, which is good
{ "$match": { "type": "chair" } },
// Unwind the array to de-normalize
{ "$unwind": "$versions" },
// Group by the document in order to get the "first" array element
{ "$group": {
"_id": "$_id",
"chairtype": { "$first": "$chairtype" },
"versions": { "$first": "$versions" }
}},
// Then group by "chairtype" to get your average values
{ "$group": {
"_id": "$chairtype",
"MID": {"$avg": "$versions.content.value"}
}}
])
Of course if your actual document has nested arrays then you will be "unwinding" and "matching" the required elements. But that is the general process of "narrowing down" the array contents to the elements you need.

Categories