combine array in php json encode - php

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

Related

how to Addition with a number all column in php array

hi i have a json file like this :
"telegram": {
"russia": {
"price": "5000",
"count": "✅ 7",
"prefix": "+7"
},"usa": {
"price": "7000",
"count": "✅ 9",
"prefix": "+1"
},
},"google": {
"russia": {
"price": "5500",
"count": "✅ 11",
"prefix": "+7"
},"usa": {
"price": "7700",
"count": "✅ 20",
"prefix": "+1"
},
}
And I want to add all the available prices to a number like 200
how i can do it?
I do this ,But this is not working :
$services = json_decode(file_get_contents("myFile.json"), true);
foreach ($services as $service) foreach ($service as $country) {
$country['price'] += 200;
echo $country['price'] . '<br>';
}
echo '<br>' . json_encode($services);
The result :
5200
7200
5700
7900
"telegram": {
"russia": {
"price": "5000",
"count": "✅ 7",
"prefix": "+7"
},"usa": {
"price": "7000",
"count": "✅ 9",
"prefix": "+1"
},
},"google": {
"russia": {
"price": "5500",
"count": "✅ 11",
"prefix": "+7"
},"usa": {
"price": "7700",
"count": "✅ 20",
"prefix": "+1"
},
}
It shows the prices correctly when I echo inside foreach, but there is no change in the array
Regarding to your comment. You miss one level loop and if you want to update the existing array, you need to pass by reference instead.
PS: unset is used in the example below because reference would be preserved after foreach and it need to be removed. Otherwise, if you use the same variable in other foreach, the reference may lead to unexpected behaviour.
<?php
$services = [
'telegram' =>
[
'russia' => ['price' => '5000', 'count' => '7', 'prefix' => '+7'],
'usa' => ['price' => '7000', 'count' => '9', 'prefix' => '+1'],
],
'google' =>
[
'russia' => ['price' => '5500', 'count' => '11', 'prefix' => '+7'],
'usa' => ['price' => '7700', 'count' => '20', 'prefix' => '+1'],
],
];
foreach ($services as &$countries) {
foreach ($countries as &$country) {
$country['price'] += 200;
unset($country);
}
unset($countries);
}
print_r($services);

Printing a foreach loop in a loop maintaining json

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",
);
}
............

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

Categories