Printing a foreach loop in a loop maintaining json - php

I have this code as I am trying to implement a json code using foreach loop
foreach ($single_google as $row) {
$data['step'][] = array(
"#type" => "HowToStep",
"url" => "https://example.com/kitchen#step1",
"name" => "Prepare the surfaces",
"itemListElement" => array(),
"image" => [
"#type" => "ImageObject",
"url" => "https://example.com/photos/1x1/photo-step1.jpg",
"height" => "406",
"width" => "305"
],
);
$all_step_google = json_decode($row["steps"]);
foreach ($all_step_google as $single_step_google) {
$data['itemListElement'][] = array(
"#type" => "HowToDirection",
"text" => "testing",
);
}
}
print_r(json_encode($data));
at the end of the coding, trying to run it I got this
{
"#type": "HowToStep",
"url": "https://example.com/kitchen#step1",
"name": "Prepare the surfaces",
"itemListElement": [],
"image": {
"#type": "ImageObject",
"url": "https://example.com/photos/1x1/photo-step1.jpg",
"height": "406",
"width": "305"
}
}
],
"itemListElement": [
{
"#type": "HowToDirection",
"text": "test."
}
instead of this which I needed actually.
{
"#type": "HowToStep",
"url": "https://example.com/kitchen#step1",
"name": "Prepare the surfaces",
"itemListElement": [
{
"#type": "HowToDirection",
"text": "Test"
}
],
"image": {
"#type": "ImageObject",
"url": "https://example.com/photos/1x1/photo-step1.jpg",
"height": "406",
"width": "305"
}
}
],
I want the "itemListElement" => array(), to print before the "image" => [] but it kept printing after the foreach loop. Please help me, am getting lost.

You use $data['itemListElement'][] = array(... on your second loop so that will assign new key to your data master array instead, the right code should be like this
............
foreach ($all_step_google as $key => $single_step_google) {
$data['step'][$key]['itemListElement'][] = array(
"#type" => "HowToDirection",
"text" => "testing",
);
}
............

Related

PHP array only showing last product within json

I have a shopping cart and once the action placeorder.php is hit, i have set-up a webhook to post to discord.
The cart uses session arrays to store the cart information.
the session array is set as below on the product.php page when the "add to card" button is pressed
$_SESSION['cart'] = array($product_id => $quantity);
The product IDs are pulled from a mysql DB.
With 2x items added to the cart, the array is as follows:
["cart"]=>
array(2) {
[1]=> int(5)
[4]=> int(3)
}
If I echo the array it comes out as
foreach ($products as $product){
echo $product[name];
echo $products_in_cart[$product['id']];
}
Output: camera5laptop3
$products_in_cart[$product['id'] is simply grabbing the quantity ordered.
The JSON Structure
I am trying to make it so that every product name in the cart appears on a new line (\n) under the "Ordered Products" field. and the same for the quanity.
This would be through a foreach but since the json structure is within json_encode() I am struggling.
The below set-up currently only shows the last $product['name'] and $products_in_cart[$product['id'] in the array
$msg = json_encode([
// Message
"content" => "",
// Username
//"username" => "",
// Avatar URL.
// Uncomment to use custom avatar instead of bot's pic
//"avatar_url" => "",
// text-to-speech
"tts" => false,
// file_upload
// "file" => "",
// Embeds Array
"embeds" => [
[
// Title
"title" => "New Order",
// Embed Type, do not change.
"type" => "rich",
// Description
"description" => "New order, go sort it",
// Link in title
//"url" => "",
// Timestamp, only ISO8601
"timestamp" => $timestamp,
// Left border color, in HEX
"color" => hexdec( "3366ff" ),
// Footer text
"footer" => [
"text" => "Sent from thestash.store",
"icon_url" => ""
],
// Embed image
"image" => [
"url" => ""
],
// thumbnail
//"thumbnail" => [
// "url" => ""
//],
// Author name & url
"author" => [
"name" => "TEST3",
"url" => ""
],
// Custom fields
"fields" => [
// Field 1
[
"name" => "Ordered Products",
"value" => $product['name'],
"inline" => true
],
// Field 2
// Field 1
[
"name" => "Quantity",
"value" => $products_in_cart[$product['id']],
"inline" => true
],
[
"name" => "Order Total $",
"value" => $subtotal,
],
[
"name" => "Customer Alias",
"value" => $_SESSION['alias'],
"inline" => true
],
[
"name" => "Customer Number",
"value" => $_SESSION['number'],
"inline" => true
],
[
"name" => "Affiliation",
"value" => $_SESSION['affiliation'],
"inline" => true
],
// etc
]
]
]
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
Current Output on discord:
Attempting to output as (manuall set in JSON)
print_r($msg);
{
"content": "",
"tts": false,
"embeds": [
{
"title": "New Order",
"type": "rich",
"description": "New order, go sort it",
"timestamp": "2023-01-13T11:57:22+00:00",
"color": 3368703,
"footer": {
"text": "Sent from thestash.store",
"icon_url": ""
},
"image": {
"url": ""
},
"author": {
"name": "TEST3",
"url": "https://thestash.store"
},
"fields": [
{
"name": "Ordered Products",
"value": "laptop",
"inline": true
},
{
"name": "Quantity",
"value": 3,
"inline": true
},
{
"name": "Order Total $",
"value": 96000
},
{
"name": "Customer Alias",
"value": "quigg",
"inline": true
},
{
"name": "Customer Number",
"value": "1239871237378127",
"inline": true
},
{
"name": "Affiliation",
"value": "yes",
"inline": true
}
]
}
]
}
Attempting to have the JSON format as follows. Where each $product[name] and $products_in_cart[$product['id']] is on a new line. Currently the last $product[name] and $products_in_cart[$product['id']] show
{
"content": "",
"tts": false,
"embeds": [
{
"title": "New Order",
"type": "rich",
"description": "New order, go sort it",
"timestamp": "2023-01-13T11:57:22+00:00",
"color": 3368703,
"footer": {
"text": "Sent from thestash.store",
"icon_url": ""
},
"image": {
"url": ""
},
"author": {
"name": "TEST3",
"url": "https://thestash.store"
},
"fields": [
{
"name": "Ordered Products",
"value": "camera\nlaptop",
"inline": true
},
{
"name": "Quantity",
"value": "5\n3",
"inline": true
},
{
"name": "Order Total $",
"value": 96000
},
{
"name": "Customer Alias",
"value": "quigg",
"inline": true
},
{
"name": "Customer Number",
"value": "1239871237378127",
"inline": true
},
{
"name": "Affiliation",
"value": "yes",
"inline": true
}
]
}
]
}
So it's just a case of adding extra things into two strings, separated by newlines. So just loop over the products array to create two strings, one for the name and one for the quantity, and put those into variables. Then, you can just use those variables in the right places in your Fields array.
Heres the general idea:
$names = "";
$quantities = "";
foreach ($products as $product){
$names .= ($names != "" ? "\n" : "").$product["name"];
$quantities .= ($quantities != "" ? "\n" : "").$products_in_cart[$product['id']];
}
Then in the bit where you build the array:
...
"fields" => [
[
"name" => "Ordered Products",
"value" => $names,
"inline" => true
],
[
"name" => "Quantity",
"value" => $quantities,
"inline" => true
],
...

How to reproduce with PHP a particular JSON document

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

Having trouble building nested JSON with PHP

I am having trouble getting these arrays to nest properly. I am grabbing all the rows from a SQL database and building an array to output in JSON for my crud app. One category has been easy, but the client now wants subcategories and that's when I hit a major wall. I am trying to nest these subcategories into categories. I can do either, but am failing to get them working together. The following is my PHP code:
while ($row = $query->fetch_assoc()) {
$categories[$row['category']][] = array(
$row['subcategory'] => $subcategories[$row['subcategory']][] = array(
'id' => $row['id'],
'item_name' => $row['item_name'],
'description' => $row['description'],
'price' => $row['price'],
),
);
}
foreach ($categories as $key => $value) {
$category_data[] = array(
'category' => $key,
'category_list' => $value,
);
}
foreach ($subcategories as $key => $value) {
$subcategory_data[] = array(
'subcategory' => $key,
'subcategory_list' => $value,
);
}
When I json_encode($category_data) I get the following JSON:
[
{
"category": "Beer",
"category_list": [
{
"Draft Beer": {
"id": "1",
"item_name": "Yuengling",
"description": "Lager. Pottstown, Pa. An American classic."
}
},
{
"Draft Beer": {
"id": "6",
"item_name": "Bud Light",
"description": "American Light Lager"
}
},
{
"Domestic Bottles": {
"id": "9",
"item_name": "Stone IPA",
"description": "India Pale Ale.<em> Escondido, Colo."
}
}
]
},
{
"category": "Wine",
"category_list": [...]
}
]
Which might work, but I would like it to join the like keys (ie: Draft Beer) into the same array. It does do that when I json_encode($subcategory_data) as shown below, but its not separated into categories, just the subcategories.
[
{
"subcategory": "Draft Beer",
"subcategory_list": [
{
"id": "1",
"item_name": "Yuengling",
"description": "Lager. Pottstown, Pa."
},
{
"id": "6",
"item_name": "Bud Light",
"description": "American Light Lager. Milwaukee, Wisc."
}
]
},
{
"subcategory": "Red Wine",
"subcategory_list": [
{
"id": "17",
"item_name": "Kendall-Jackson",
"description": "Cabernet Sauvignon, 2010."
},
{
"id": "18",
"item_name": "Sanford",
"description": "Pinot Noir, 2011. Lompoc, Calif"
}
]
},
{
"subcategory": "Domestic Bottles",
"subcategory_list": [
{
"id": "9",
"item_name": "Stone IPA",
"description": "India Pale Ale. Escondido, Colo."
},
{
"id": "10",
"item_name": "Blue Moon",
"description": "Belgian-style Wheat Ale."
}
]
}
]
So my question is why does it merge in the second set of data but not the first. How do I get the subcategory_data into the category_data. Any help id truly appreciated. Below is an example if what I am looking for:
{
"category_name":"Beer",
"category_list" : [
{
"subcategory_name": "Draft Beer",
"subcategory_list": [
{
"id": "1",
"item_name": "Yuengling",
"description": "Lager. Pottstown, Pa."
},
{
"id": "6",
"item_name": "Bud Light",
"description": "American Light Lager. Milwaukee, Wisc."
}
}
]
},
{
"category_name":"Wine",
"category_list" : [
{
"subcategory_name": "Red Wine",
"subcategory_list": [...]
}
]
}
Thanks for looking, I am fairly new to PHP and am relying on my javascript skills.
First, try var_dump($categories). You'll see that you're building a rather weird data structure (you have arrays of 1-element arrays...). The following code will build a simpler structure:
$categories[$row['category']][$row['subcategory']][] = array(
'id' => $row['id'],
'item_name' => $row['item_name'],
'description' => $row['description'],
'price' => $row['price'],
);
This will serialize to JSON that's probably acceptable as is:
{
"Beer": {
"Draft Beer": [
{
"id": "1",
"item_name": "Yuengling",
"description": "Lager. Pottstown, Pa."
},
{
"id": "6",
"item_name": "Bud Light",
"description": "American Light Lager. Milwaukee, Wisc."
}
],
...
An additional transformation gets the data in the format you asked for:
foreach ($categories as $category_name => $subcategories) {
$subcategory_data = array();
foreach ($subcategories as $subcategory_name => $items) {
$subcategory_data[] = array(
'subcategory_name' => $subcategory_name,
'subcategory_list' => $items
);
}
$category_data[] = array(
'category_name' => $category_name,
'category_items' => $subcategory_data
);
}

Reformatting Json to geoJson in PHP (Laravel)

I have laravel outputting the following:
[
{
"id": 3,
"lat": "38.8978378",
"lon": "-77.0365123"
},
{
"id": 4,
"lat": "44.8",
"lon": "1.7"
},
{
"id": 22,
"lat": "37.59046",
"lon": "-122.348994"
}
]
i would like it to be the geoJson format:
{ "type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [lat, lon]},
"properties": {
"name": "value"
}
}
]
}
I know i need some sort of loop. But i'm not sure how to structure it in PHP. Any guidance would be greatly appreciated. Trying to build a map application that could have several thousand markers on a world view. I'm already thinking about clustering, but need to get past this basic step.
Thanks!
I modified the loop, the arrangement was a bit off. And turned it into a function if anyone is interested:
function geoJson ($locales)
{
$original_data = json_decode($locales, true);
$features = array();
foreach($original_data as $key => $value) {
$features[] = array(
'type' => 'Feature',
'geometry' => array('type' => 'Point', 'coordinates' => array((float)$value['lat'],(float)$value['lon'])),
'properties' => array('name' => $value['name'], 'id' => $value['id']),
);
};
$allfeatures = array('type' => 'FeatureCollection', 'features' => $features);
return json_encode($allfeatures, JSON_PRETTY_PRINT);
}
Just use json_decode() on the original values and rebuild/reconstruct a new one. Consider this example:
$original_json_string = '[{"id": 3,"lat": "38.8978378","lon": "-77.0365123"},{"id": 4,"lat": "44.8","lon": "1.7"},{"id": 22,"lat": "37.59046","lon": "-122.348994"}]';
$original_data = json_decode($original_json_string, true);
$coordinates = array();
foreach($original_data as $key => $value) {
$coordinates[] = array('lat' => $value['lat'], 'lon' => $value['lon']);
}
$new_data = array(
'type' => 'FeatureCollection',
'features' => array(
'type' => 'Feature',
'geometry' => array('type' => 'Point', 'coordinates' => $coordinates),
'properties' => array('name' => 'value'),
),
);
$final_data = json_encode($new_data, JSON_PRETTY_PRINT);
print_r($final_data);
$final_data should yield something like:
{
"type": "FeatureCollection",
"features": {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
{
"lat": "38.8978378",
"lon": "-77.0365123"
},
{
"lat": "44.8",
"lon": "1.7"
},
{
"lat": "37.59046",
"lon": "-122.348994"
}
]
},
"properties": {
"name": "value"
}
}
}

combine array in php json encode

I develop php code like this :
while($row = mysql_fetch_array ($result))
{
$catalogue = array(
'catalogue_id' => $row[0],
'catalogue_name' => $row[1],
'catalogue_cover' => $row[2],
'category' => array(
'id' => $row[3],
'name' => $row[4],
'cover' => $row[5],
'item' => array (
'id' => $row[6],
'name' => $row[7],
'cover' => $row[8],
'description' => $row[9],
'price' =>$row[10]
)
),
);
array_push($json, $catalogue);
}
$jsonresult = array2json($json);
echo $jsonresult;
The result json is :
[
{
"catalogue_id": "59",
"catalogue_name": "IT Catalog",
"catalogue_cover": "http://192.168.0.22:90/Ecatalogue/catalogue/covers/511b21f398969.jpeg",
"category": {
"id": "60",
"name": "Computer Accessory",
"cover": "http://192.168.0.22:90/Ecatalogue/category/covers/511b2e11e8b26.jpg",
"item": {
"id": "61",
"name": "CD",
"cover": "http://192.168.0.22:90/Ecatalogue/item/covers/511b2e1da3063.jpg",
"description": "",
"price": "0.00"
}
}
},
{
"catalogue_id": "59",
"catalogue_name": "IT Catalog",
"catalogue_cover": "http://192.168.0.22:90/Ecatalogue/catalogue/covers/511b21f398969.jpeg",
"category": {
"id": "61",
"name": "IT Category",
"cover": "http://192.168.0.22:90/Ecatalogue/category/covers/511caf7329f63.jpeg",
"item": {
"id": "63",
"name": "IT Item",
"cover": "http://192.168.0.22:90/Ecatalogue/item/covers/511cafa17cce5.jpeg",
"description": "",
"price": "0.00"
}
}
}
]
But I want to combine the same catalog like this :
[
{
"catalogue_id": "59",
"catalogue_name": "IT Catalog",
"catalogue_cover": "http://192.168.0.22:90/Ecatalogue/catalogue/covers/511b21f398969.jpeg",
"category": {
"id": "60",
"name": "Computer Accessory",
"cover": "http://192.168.0.22:90/Ecatalogue/category/covers/511b2e11e8b26.jpg",
"item": {
"id": "61",
"name": "CD",
"cover": "http://192.168.0.22:90/Ecatalogue/item/covers/511b2e1da3063.jpg",
"description": "",
"price": "0.00"
},
"category-2": {
"id": "61",
"name": "IT Category",
"cover": "http://192.168.0.22:90/Ecatalogue/category/covers/511caf7329f63.jpeg",
"item": {
"id": "63",
"name": "IT Item",
"cover": "http://192.168.0.22:90/Ecatalogue/item/covers/511cafa17cce5.jpeg",
"description": "",
"price": "0.00"
}
}
}
}
]
How can I do that ?
You can index the $catalogue by catalogue_id and append category as they come
while ($row = mysql_fetch_array($result)) {
$catalogue_id = $row[0];
if (!isset($json[$catalogue_id])) {
$json[$catalogue_id] = array(
'catalogue_id' => $catalogue_id,
'catalogue_name' => $row[1],
'catalogue_cover' => $row[2]
'categories' => array();
);
}
$json[$catalogue_id]['categories'][] = array(
'id' => $row[3],
'name' => $row[4],
'cover' => $row[5],
'item' => array (
'id' => $row[6],
'name' => $row[7],
'cover' => $row[8],
'description' => $row[9],
'price' =>$row[10]
);
}
$jsonresult = array2json(array_values($json));
echo $jsonresult;
Instead of array2json you could also use json_encode
echo json_encode(array_values($json));

Categories