Give name to array in Json/PHP - php

In AJAX I retrieve in database the last date of a document by category (for example the category invoice, orders, etc.) thanks to this request:
  // In each category there can be several documents
$stmt = $bdd->prepare('SELECT file_name, max(file_creation) as file_creation, file_category
FROM all_files
WHERE ...
GROUP BY file_category');
$stmt ->execute(array(
...
));
$arr = $stmt->fetchAll();
echo json_encode($arr);
So I get it back in JSON:
[
   {
      "File_name": "order_18"
      "0": "order_18"
      "File_creation": "2018-11-28"
      "1": "2018-11-28"
      "File_category": invoice "
      "3": invoice "
   }
   {
      "File_name": "order_18"
      "0": "order_18"
      "File_creation": "2018-11-25"
      "1": "2018-11-25"
      "File_category": "order"
      "3": "order"
   }
]
I then want to place each data in the right places with jquery, like this:
$ ('#label-order').text('') // the text will have to be: 2018-11-25
$ ('#label-invoice').text('') // the text will have to be: 2018-11-28
The problem is that I do not know how to recover the data that interests me to put it in the right places because the number of categories will increase over time
So I thought of doing something like that, to get the data back to data ["invoice"] ["file_creation"] and data ["order"] ["file_creation"]:
[
   "invoice": {
      "File_name": "order_18"
      "0": "order_18"
      "File_creation": "2018-11-28"
      "1": "2018-11-28"
      "File_category": invoice "
      "3": invoice "
   }
   "order": {
      "File_name": "order_18"
      "0": "order_18"
      "File_creation": "2018-11-25"
      "1": "2018-11-25"
      "File_category": "order"
      "3": "order"
   }
]
Is that possible? If so, how can I do?
Is there a better solution?

Here is a code to have in a result list of invoices and orders separately.
After receiving data on front-end you can use simple code to group all items:
var data = [
{
"File_name": "order_18",
"0": "order_18",
"File_creation": "2018-11-28",
"1": "2018-11-28",
"File_category": "invoice",
"3": "invoice "
},
{
"File_name": "order_18",
"0": "order_18",
"File_creation": "2018-11-25",
"1": "2018-11-25",
"File_category": "order",
"3": "order"
}
]
var categories = {
invoices: [],
orders: []
}
data.map((item) => {
if(item['File_category'] === 'order') {
categories.orders.push(item)
} else if(item['File_category'] === 'invoice') {
categories.invoices.push(item)
}
})
console.log(categories)
Than you can just loop over specific categories like categories.invoices or categories.orders and easily append it to body.

Doing this using the PHP code:
<?php
//$arrays = $stmt->fetchAll();
$arrays=
[
[
"File_name"=>"order_18",
"File_creation"=>"2018-11-28",
"File_category"=>"invoice",
],
[
"File_name"=>"order_18",
"File_creation"=>"2018-11-25",
"File_category"=>"order",
]
];
foreach($arrays as $index=>$array)
{
if(isset($array["File_category"]))
{
$key=$array["File_category"];
unset($array["File_category"]);
$arrays[$key][] = $array;
unset($arrays[$index]);
}
}
print_r($arrays);
//echo json_encode($arrays);
?>
The result will be:
Array
(
[invoice] => Array
(
[0] => Array
(
[File_name] => order_18
[File_creation] => 2018-11-28
)
)
[order] => Array
(
[0] => Array
(
[File_name] => order_18
[File_creation] => 2018-11-25
)
)
)

Related

How can I build an multi-dimentional array from a wpdb query return?

I am trying to build a multi-dimensional array from a query return and ran into a problem. Here is a sanitized snippet similar to what I am trying to do. My problem is building the sub array. Any suggestions to get my desired output? I used JSON so it would be more obvious. I can parse an array or JSON.
<?php
// this is my query
global $wpdb;
$locationData = $wpdb->get_results("SELECT
locations.locationID,
locations.location_name,
locations.city,
locations.state,
locations.products,
locations.type,
locations.sku
");
// which returns something like
// [locationID] [location_name] [city] [state] [products] [type] [sku]
// 001 Tulsa Outlet Tulsa OK cakes chocolate 3763
// 001 Tulsa Outlet Tulsa OK cakes lemon 3765
// 001 Tulsa Outlet Tulsa OK sodas coke 4983
// 001 Tulsa Outlet Tulsa OK sodas sprite 4950
// and so on..
// I build an array to be consumed by another function that I created in my plugin:
foreach( $locationData as $key => $location ) {
$output[$row['locationID']] = array(
'locationID' => $row['locationID'],
'location_name' => $row['location_name'],
'products' => array(
// this is where my previous attempts broke down
)
);
$output[$key]['city'] = $location->city;
$output[$key]['state'] = $location->state;
}
// and the $output I need would look like this:
{
"locations" : [
{
"locationID" : "001",
"location_name" : "Tulsa Outlet",
"products" : {
"cakes" : {
"chocolate" : "3763",
"lemon" : "3765"
},
"sodas" : {
"coke" : "4983",
"sprite" : "4950"
}
},
"city" : "Tulsa",
"state" : "ok"
}
]
}
?>
These should help:
$output = [];
foreach ($locationData as $location) {
$locId = $location->locationID;
if (empty($output[$locId])) {
$output[$locId] = [
'locationID' => $location->locationID,
'location_name' => $location->location_name,
'city' => $location->city,
'state' => $location->state,
'products' => [],
];
}
$productType = $location->products;
if (empty($output[$locId]['products'][$productType])) {
$output[$locId]['products'][$productType] = [];
}
$output[$locId]['products'][$productType][$location->type] = $location->sku;
}
Not really sure what you use - $row or $location, so changed everything to $location.
To reindex $output to 0-index array, use array_values.

MongoDB\Driver php How to make inner join with filter in the first collection

I need to make a join between two collections at the same time i need to execute filter for the first collection , exemple :
... // code inside my classe
$this->MDBManager = new MongoDB\Driver\Manager("mongodb:// xxxxx: xxxxx #" . $this->host);
$filter = array ("date", array('$gte' =>str_replace("-","/", "2019-10-5") , '$lte' => str_replace("-","/", 2019-10-15)))
$this->MDBQuery = new MongoDB\Driver\Query($filters, $options);
$this->results = $this->MDBManager->executeQuery("mydb.colllection1", $this->MDBQuery);
so this is my first collection and i need to join the soconde collection id to matche the same value of productEnsembleId attribute in collection 1.
The join request need to be in only one request .
Thnak you so much for your help .
For more details :
exemple collection 1 :
{
"_id": "5db8683c877c34001559f192",
"id": "1BuVJCLGIUIcDXfBQVlpzccAP6r2JRQPGL4wHTEfPildnnWU5gUh8oymfJM2a6wOW117sTbzWJGKLNaRCZ7uMNHA2CnBjT4PeM44B9QaNYMZfg1BiiBa5JYBRLxMLxFTOY88PDFm4U4yDn9iPnljRnfeqpu9ZBl7fGS4tnnlmuz2ntlXb6cFFrFmQIo8EpDOwr5LLyaSrI67mLUya94WMUnDOojXpf4UAjcmMTayM4x9fmla_00001572366396",
"userId": "DEXpMPBstW37YkixF5e6yPeVpkElumYN1nyw0rjjcPy6vf8mdUHXzIg8KMvy0KegxThD5LgKS6WnuhvPwbLqa3aoyhVgIOhk0huqvxmQ0ctBFMVZZyaPkADdGmWUFM10OhTo919uQOb4QgZLZjtDOnTkcmLUfB6uLFdfNmaXLRNaRs6w4GI9ZDwnuVWAgQ3uajWnUTigq1gXbKGcI4G4Es8cBKZsVQhxsKzOqLFGXDONbQEX_00000000000000",
"productEnsembleId": "8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166",
"date": "2019/11/01",
"status": "En cours"
}
exmple collextion 2 :
{
"_id": "5da8948e877c34001529a7f2",
"id": "8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166",
"name": "ensemble 2",
"image": "fjO9sb3FUmDFhgWn49v1Io5Oa5sdFyL7KZRVzsH0n06n7GtNqIPdFSfDT67BSIvfYSmdTh7IoYyize3SDX169cas4MWMwVWLsF989ZWy76ANsYS4tkLS5OYR1i2TrqXjP40WDCcWvr6OkQapgzuk4hAISx7Mwf6Wp2Z3krzjn72PrTXUDmG7nDrp7VKDrsonCVqkmGs7lAwocdEeghWs7NUVkMdIGMjWDVo8u3wlClzs2e5X_00001571329177",
"produits": null
}
So assuming you want the join results for one document in the first collection, here is a mongo shell query.
db.col1.aggregate([
{ $match: { "_id": "5db8683c877c34001559f192" } },
{ $lookup: {
from: "col2",
localField: "productEnsembleId",
foreignField: "id",
as: "col2_data"
}
}
])
The results look like ...
{
"_id" : "5db8683c877c34001559f192",
"id" : "1BuVJCLGIUIcDXfBQVlpzccAP6r2JRQPGL4wHTEfPildnnWU5gUh8oymfJM2a6wOW117sTbzWJGKLNaRCZ7uMNHA2CnBjT4PeM44B9QaNYMZfg1BiiBa5JYBRLxMLxFTOY88PDFm4U4yDn9iPnljRnfeqpu9ZBl7fGS4tnnlmuz2ntlXb6cFFrFmQIo8EpDOwr5LLyaSrI67mLUya94WMUnDOojXpf4UAjcmMTayM4x9fmla_00001572366396",
"userId" : "DEXpMPBstW37YkixF5e6yPeVpkElumYN1nyw0rjjcPy6vf8mdUHXzIg8KMvy0KegxThD5LgKS6WnuhvPwbLqa3aoyhVgIOhk0huqvxmQ0ctBFMVZZyaPkADdGmWUFM10OhTo919uQOb4QgZLZjtDOnTkcmLUfB6uLFdfNmaXLRNaRs6w4GI9ZDwnuVWAgQ3uajWnUTigq1gXbKGcI4G4Es8cBKZsVQhxsKzOqLFGXDONbQEX_00000000000000",
"productEnsembleId" : "8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166",
"date" : "2019/11/01",
"status" : "En cours",
"col2_data" : [
{
"_id" : "5da8948e877c34001529a7f2",
"id" : "8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166",
"name" : "ensemble 2",
"image" : "fjO9sb3FUmDFhgWn49v1Io5Oa5sdFyL7KZRVzsH0n06n7GtNqIPdFSfDT67BSIvfYSmdTh7IoYyize3SDX169cas4MWMwVWLsF989ZWy76ANsYS4tkLS5OYR1i2TrqXjP40WDCcWvr6OkQapgzuk4hAISx7Mwf6Wp2Z3krzjn72PrTXUDmG7nDrp7VKDrsonCVqkmGs7lAwocdEeghWs7NUVkMdIGMjWDVo8u3wlClzs2e5X_00001571329177",
"produits" : null
}
]
}
which is a combination of collection 1 and collection 2. If you want all records from collection 1 simply remove the $match criteria.
Edit: Include PHP version of same query above...
To use this query in a PHP page see below. This example assumes using the latest MongoDB driver and strategies including using PHP Composer...
<?php
require 'vendor/autoload.php';
$client = new MongoDB\Client('mongodb://johndoe:mypassword#localhost:27017');
$collection = $client->ensemble->col1;
$cursor = $collection->aggregate(
array(
array( '$match' => array( '_id' => '5db8683c877c34001559f192' ) ),
array(
'$lookup' => array(
'from' => 'col2',
'localField' => 'productEnsembleId',
'foreignField' => 'id',
'as' => 'col2_data'
)
)
)
);
foreach($cursor as $document) {
print_r($document);
}
?>
PHP Results:
MongoDB\Model\BSONDocument Object
(
[storage:ArrayObject:private] => Array
(
[_id] => 5db8683c877c34001559f192
[id] => 1BuVJCLGIUIcDXfBQVlpzccAP6r2JRQPGL4wHTEfPildnnWU5gUh8oymfJM2a6wOW117sTbzWJGKLNaRCZ7uMNHA2CnBjT4PeM44B9QaNYMZfg1BiiBa5JYBRLxMLxFTOY88PDFm4U4yDn9iPnljRnfeqpu9ZBl7fGS4tnnlmuz2ntlXb6cFFrFmQIo8EpDOwr5LLyaSrI67mLUya94WMUnDOojXpf4UAjcmMTayM4x9fmla_00001572366396
[userId] => DEXpMPBstW37YkixF5e6yPeVpkElumYN1nyw0rjjcPy6vf8mdUHXzIg8KMvy0KegxThD5LgKS6WnuhvPwbLqa3aoyhVgIOhk0huqvxmQ0ctBFMVZZyaPkADdGmWUFM10OhTo919uQOb4QgZLZjtDOnTkcmLUfB6uLFdfNmaXLRNaRs6w4GI9ZDwnuVWAgQ3uajWnUTigq1gXbKGcI4G4Es8cBKZsVQhxsKzOqLFGXDONbQEX_00000000000000
[productEnsembleId] => 8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166
[date] => 2019/11/01
[status] => En cours
[col2_data] => MongoDB\Model\BSONArray Object
(
[storage:ArrayObject:private] => Array
(
[0] => MongoDB\Model\BSONDocument Object
(
[storage:ArrayObject:private] => Array
(
[_id] => 5da8948e877c34001529a7f2
[id] => 8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166
[name] => ensemble 2
[image] => fjO9sb3FUmDFhgWn49v1Io5Oa5sdFyL7KZRVzsH0n06n7GtNqIPdFSfDT67BSIvfYSmdTh7IoYyize3SDX169cas4MWMwVWLsF989ZWy76ANsYS4tkLS5OYR1i2TrqXjP40WDCcWvr6OkQapgzuk4hAISx7Mwf6Wp2Z3krzjn72PrTXUDmG7nDrp7VKDrsonCVqkmGs7lAwocdEeghWs7NUVkMdIGMjWDVo8u3wlClzs2e5X_00001571329177
[produits] =>
)
)
)
)
)
)

Need help parsing JSON output

I'm making a REST call in PHP and returning JSON. I'm eventually putting this into tables, but trying to output the value for now to get the hang of it.
There are values in the "data" field I would like to get into variables. In my example they would be "201807", 23.43 and "201806", 22.54. It's the first two values of the property "data"
My code looks like this:
<?php
$service_url = "http://api.eia.gov/geoset/?geoset_id=ELEC.PRICE.RES.M&regions=USA-AL,USA-AK,USA-AR&api_key=3a8b92cfaf3a21e2e990f228c9152eeb&out=json&start=2018";
$get_data = callAPI('GET', $service_url, false);
$response = json_decode($get_data);
foreach ($response as $r) {
echo $row->name;
echo $row->geoset_id;
}
?>
And JSON looks like this:
{
"geoset": {
"geoset_id": "ELEC.PRICE.RES.M",
"setname": "Average retail price of electricity : residential : monthly",
"f": "M",
"units": "cents per kilowatthour",
"unitsshort": null,
"series": {
"USA-AK": {
"series_id": "ELEC.PRICE.AK-RES.M",
"name": "Average retail price of electricity : Alaska : residential : monthly",
"region": "USA-AK",
"latlon": null,
"unitsshort": null,
"start": "200101",
"end": "201807",
"data": [
["201807", 23.43],
["201806", 22.54],
["201805", 22.16],
["201804", 21.61],
["201803", 21.47],
["201802", 21.11],
["201801", 21.67]
]
},
"USA-AL": {
"series_id": "ELEC.PRICE.AL-RES.M",
"name": "Average retail price of electricity : Alabama : residential : monthly",
"region": "USA-AL",
"latlon": null,
"unitsshort": null,
"start": "200101",
"end": "201807",
"data": [
["201807", 12.28],
["201806", 12.41],
["201805", 12.49],
["201804", 12.79],
["201803", 12.65],
["201802", 12.29],
["201801", 11.59]
]
},
"USA-AR": {
"series_id": "ELEC.PRICE.AR-RES.M",
"name": "Average retail price of electricity : Arkansas : residential : monthly",
"region": "USA-AR",
"latlon": null,
"unitsshort": null,
"start": "200101",
"end": "201807",
"data": [
["201807", 9.98],
["201806", 9.99],
["201805", 9.89],
["201804", 10],
["201803", 10.47],
["201802", 9.8],
["201801", 9.36]
]
}
}
}
}
So far I'm getting NULL values back.
As you have used json_decode your result will be convert to object type. so you should do as follows:
$geoset = $response->geoset;
$geosetid = $geoset->geoset_id;
foreach ($geoset->series as $row) {
echo $row->name;
$data = $row->data; //this will produce the values as array
}
Your data array will be like this:
Array
(
[0] => Array
(
[0] => 201807
[1] => 23.43
)
[1] => Array
(
[0] => 201806
[1] => 22.54
)
)
...
Hopefully this helps! :)
Your code will never work, because:
You iterate $response as $r, but use $row inside;
The $response has only one child: geoset. There is no $response->name neither $response->geoset_id.
If you want the geoset_id, you must access using: $response->geoset->geoset_id.
To achieve this:
There are values in the "data" field I would like to get into variables
Use the following code:
foreach ($response->geoset->series as $series) {
foreach ($series->data as $data) {
$date = $data[0];
$value = $data[1];
}
}

getting relational results from three tables into one nested array

i have googled for solution to my problem but nun helped me.
here i have three tables items, feeds and images. each item has one feed and one or more images.
i have 3 functions. one is to return records from items table the second one receives feeds_id (foreign key in items table) then return records from feeds table. the third function is to return all images related to items_id.
those functions are :
* To get all items in database:
function get_items(){
return $query = Database::getInstance('db')
->table('items')
->columns(
'id',
'items.rowid',
'items.feed_id as feed_id',
'title' )
->findAll();
}
* To get feed data from feeds table :
function get_feeds($id){
return $query = Database::getInstance('db')
->table('feeds')
->eq('id',$id)
->findAll();
}
* To get image data from images table :
function get_images($id){
return $query = Database::getInstance('db')
->table('images')
->columns('items_id','src as image_url',
'title as image_title',
'alt')
->eq('items_id',$id)
->findAll();
}
Then i have the following code to call those function and display the result in jsonformat:
$response['items'] = array();
$response['feeds'] = array();
$response['images'] = array();
foreach ($items = get_items() as $item) {
$response['items'][] = array(
'id' => (int)$item['rowid'],
'feed_id' => (int)$item['feed_id'],
'title' => $item['title'],
);
foreach ($feeds = get_feeds((int)$item['feed_id']) as $feed) {
$response['feeds'][] = array(
'title' => $feed['title'],
'logo_url' => $feed['logo_url'],
'site_url' => $feed['site_url'],
);
}
foreach ($images = get_images($item['id']) as $image) {
$response['images'][] = array(
'id' => $image['items_id'],
'url' => $image['image_url'],
'thumb' => $_SERVER['SERVER_NAME'] . /myServer/images/thumbs/'. 'thumb_'.basename($image['image_url']),
'title' => $image['image_title'],
'alt' => $image['alt']
);
}
}
echo json_encode($response, JSON_PRETTY_PRINT);
so, my expectation is to get json output like:
"items": [
{
"id": ,
"feed_id":
"title":
"feeds": [
{
"title": ,
"logo_url": ,
"site_url": "
}
]
"images": [
{
"id": ,
"url": ",
"thumb":
"title": "",
"alt": ""
},
{
....
}
]
}]
i mean each item array should include nested arrays of its related data coming from get_feeds and get_images functions.
instead of that, i get response like :
//here i select two items from my db
"items": [
{ //first_item
"id": ,
"feed_id":
"title":
},
{ //second_item
"id": ,
"feed_id":
"title":
}
],
"feeds": [
{ // feed data for first item
"title": ,
"logo_url": ,
"site_url": "
},
{ // feed data for second item
"title": ,
"logo_url": ,
"site_url": "
}
],
"images": [
{ // image data for first item
"id": ,
"url": ",
"thumb":
"title": "",
"alt": ""
},
{ // other images data
....
}
]
}]
as you see i am getting output without keeping relation between items, feeds and images, all of them are shown independently.
my queries are fine but i am suspecting error in my foreach statements.
i could fix this issue by joining those tree tables in one query, but i don't want to do that because i need to do validation and other operations to output comes from each table.
i appreciate your help
i found the solution. it is very easy :)
it is just like:
$response['items'][] = array(
'id' => (int)$item['rowid'],
'feed_id' => (int)$item['feed_id'],
'title' => $item['title'],
'feeds' => array(
)
'images' => array(
)
);

Create nested json object using php mysql

I have two tables, table 1 has 2 fields (question_pk, question_name) and table 2 has 4 fields(ans_pk, options, question_fk and right_answer). I want to create json like the following structure
{
"type": "quiz",
"name": "Brand Colors",
"description": "Can you identify these brands by the background color?",
"questions": [
{
"name": "Can you identify this color?",
"description": "#ea4c89",
"answers": [
{
"name": "Dribbble",
"description": "dribbble.png",
"weight": 1
},
{
"name": "Amazon",
"description": "amazon.png",
"weight": 0
},
{
"name": "Apple",
"description": "apple.png",
"weight": 0
}
]
},
{
"name": "Can you identify this color?",
"description": "#3d9ae8",
"answers": [
{
"name": "Youtube",
"description": "youtube.png",
"weight": 0
},
{
"name": "Dropbox",
"description": "dropbox.png",
"weight": 1
},
{
"name": "Wordpress",
"description": "wordpress.png",
"weight": 0
}
]
},
{
"name": "Can you identify this color?",
"description": "#c4302b",
"answers": [
{
"name": "Youtube",
"description": "youtube.png",
"weight": 1
},
{
"name": "Twitter",
"description": "twitter.png",
"weight": 0
},
{
"name": "Vimeo",
"description": "vimeo.png",
"weight": 0
}
]
}
]
}
MY PHP CODE
<?php
include '../config/config.php';
if(isset($_GET['sub_cat_id']))
{
$sub_cat_id = $_GET['sub_cat_id'];
$result = mysql_query("select * from $questions where sub_cat='$sub_cat_id' order by level_fk asc");
$json_response = array(); //Create an array
$i=1;
while ($row = mysql_fetch_array($result))
{
$row_array['qus_pk'] = $row['qus_pk'];
$row_array['question'] = $row['question'];
$qus_pk = $row['qus_pk'];
$option_qry = mysql_query("select * from $qus_ans where qus_pk=$qus_pk");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array['options'] = $opt_fet['options'];
$row_array['right_ans'] = $opt_fet['right_ans'];
array_push($json_response,$row_array); //push the values in the array
}
$i++;
}
echo json_encode($json_response);
}
?>
And My Result I am getting json response like the following
[
{
"qus_pk": "1",
"question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
"options": "45",
"right_ans": "0"
},
{
"qus_pk": "1",
"question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
"options": "40",
"right_ans": "0"
},
{
"qus_pk": "1",
"question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
"options": "35",
"right_ans": "1"
},
{
"qus_pk": "1",
"question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
"options": "50",
"right_ans": "0"
},
{
"qus_pk": "2",
"question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
"options": "4 times",
"right_ans": "0"
},
{
"qus_pk": "2",
"question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
"options": "1 times",
"right_ans": "0"
},
{
"qus_pk": "2",
"question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
"options": "3 times",
"right_ans": "1"
},
{
"qus_pk": "2",
"question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
"options": "5 times",
"right_ans": "0"
}
]
In my respose each time the question is repeated so how to avoid and if i want to achive the first json structure, in my PHP code what&where i need to make changes?. If any one knows help me.
Hi try this,
<?php
include '../config/config.php';
if(isset($_GET['sub_cat_id']))
{
$sub_cat_id = $_GET['sub_cat_id'];
$result = mysql_query("SELECT * FROM $questions WHERE sub_cat='$sub_cat_id' ORDER BY level_fk ASC");
$json_response = array(); //Create an array
while ($row = mysql_fetch_array($result))
{
$row_array = array();
$row_array['qus_pk'] = $row['qus_pk'];
$row_array['question'] = $row['question'];
$row_array['answers'] = array();
$qus_pk = $row['qus_pk'];
$option_qry = mysql_query("SELECT * FROM $qus_ans WHERE qus_pk=$qus_pk");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array['answers'][] = array(
'options' => $opt_fet['options'],
'right_ans' => $opt_fet['right_ans'],
);
}
array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response);
}
?>
I think this code is easier to figure out and by the way it uses mysqli ...
This is based on my own data structure, I am in the middle of something and I have no time a.t.m. to adapt it to the question but should easy to figure out how to adapt it to other structures :
$usersList_array =array();
$user_array = array();
$note_array = array();
$fetch_users = mysqli_query($mysqli, "SELECT
ID,
Surname,
Name
FROM tb_Users
WHERE Name LIKE 'G%'
ORDER BY ID") or die(mysqli_error($mysqli));
while ($row_users = mysqli_fetch_assoc($fetch_users)) {
$user_array['id'] = $row_users['ID'];
$user_array['surnameName'] = $row_users['Surname'].' '.$row_users['Name'];
$user_array['notes'] = array();
$fetch_notes = mysqli_query($mysqli, "SELECT
id,
dateIns,
type,
content
FROM tb_Notes
WHERE fk_RefTable = 'tb_Users' AND
fk_RefID = ".$row_users['ID'].""
) or die(mysqli_error($mysqli));
while ($row_notes = mysqli_fetch_assoc($fetch_notes)) {
$note_array['id']=$row_notes['id'];
$note_array['dateIns']=$row_notes['dateIns'];
$note_array['type']=$row_notes['type'];
$note_array['content']=$row_notes['content'];
array_push($user_array['notes'],$note_array);
}
array_push($usersList_array,$user_array);
}
$jsonData = json_encode($usersList_array, JSON_PRETTY_PRINT);
echo $jsonData;
Resulting JSON :
[
{
"id": "1",
"surnameName": "Xyz Giorgio",
"notes": [
{
"id": "1",
"dateIns": "2016-05-01 03:10:45",
"type": "warning",
"content": "warning test"
},
{
"id": "2",
"dateIns": "2016-05-18 20:51:32",
"type": "error",
"content": "error test"
},
{
"id": "3",
"dateIns": "2016-05-18 20:53:00",
"type": "info",
"content": "info test"
}
]
},
{
"id": "2",
"cognomeNome": "Xyz Georg",
"notes": [
{
"id": "4",
"dateIns": "2016-05-20 14:38:20",
"type": "warning",
"content": "georg warning"
},
{
"id": "5",
"dateIns": "2016-05-20 14:38:20",
"type": "info",
"content": "georg info"
}
]
}
]
A basic class to handle nesting tables into a php array.
PHP CLASS
// chain data into a php array, filtering by relation to parent, based on a structure definition array
// nest child data by relation to parent data
// assign a array label "arr_label" to child definition to define what key the filtered data will use
// assign a parent key "p_key" and a child key "c_key" to child definition to assign connection points from child to parent
// load array data to filter into "arr" key on child definition
class class_chain_filter
{
var $return_arr;
function __construct()
{
} // CONSTRUCTOR
// input a defined filter tree array and output a processed result
function chain_filter($filter_tree)
{
// can feed either a single record a set of rows...
if(!$this->is_assoc($filter_tree['arr']))
$this->return_arr = $filter_tree['arr']; // root for return array
else
$this->return_arr[] = $filter_tree['arr']; // force a numeric array so return is consistent.
$this->do_chain_filter( $filter_tree['next_arrs'], $this->return_arr );
return $this->return_arr;
} // $this->chain_filter($filter_tree) // public
function is_assoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
function do_chain_filter(&$tree_arr, &$final_arr)
{
$cur_final_node = &$final_arr;
if( !is_array($cur_final_node) )
return false;
// send the next_arrs
foreach($final_arr as $f_key => $f_arr)
{
$cur_final_node = &$final_arr[$f_key];
foreach($tree_arr as $n_key => $n_arr)
{
$cur_tree_node = $tree_arr[$n_key];
// $final_cur_el['arr_label'] = 'true';
$next_final_node = &$cur_final_node[$cur_tree_node['arr_label']];
// data up hombre
// filter out array elements not related to parent array
$result = $this->children_of_parent(
$cur_final_node,
$cur_tree_node['arr'],
$cur_tree_node['p_key'],
$cur_tree_node['c_key']
);
$next_final_node = $result;
// now recurse if we have more depths to travel...
if(!empty($cur_tree_node['next_arrs']))
$this->do_chain_filter($cur_tree_node['next_arrs'], $next_final_node);
}
}
} // this->function chain_filter(&$tree_arr, &$final_arr)
// take 2 arrays
// first array is an associative array.
// second array is an array of associative arrays.
// return children of second array that belong to parent array
function children_of_parent($arr_parent, $arr_children, $key_parent, $key_child )
{
// parent = a record
// child = multiple records
// filter out children that don't apply to parent.
// return the result
$parent_id = $arr_parent[$key_parent];
foreach($arr_children as $arr_child)
{
$child_id = $arr_child[$key_child];
if($child_id == $parent_id)
$return_arr[] = $arr_child;
}
if(!empty($return_arr))
return $return_arr;
} // this->children_of_parent($arr_parent, $arr_children, $key_parent, $key_child )
} // end. class class_chain_filter
LOAD UP SOME TABLES (USE YOUR OWN PREFERRED DB CLASS)
$areas = $db->get("SELECT * FROM areas");
$rooms = $db->get("SELECT * FROM rooms");
$exits = $db->get("SELECT * FROM exits");
DEFINE OUR RETURNED ARRAY TREE STRUCTURE
// predefine tree structure for generation
// structure definition array example...
$tree_arr = array (
"arr" => $areas, // root (can be multiple rows or a single record)
"next_arrs" => array ( // children
0 => array(
"arr" => $rooms, // array to filter against parent
"arr_label" => "rooms", // for the php array label
"p_key" => "id", // field name of parent // eg) id
"c_key" => "areaid", // this array's field name that links it to parent
"next_arrs" => array( // children
0 => array(
"arr" => $exits, // array to filter against parent
"arr_label" => "exits", // for the php array label
"p_key" => "id", // field name of parent / blank if root / eg) id
"c_key" => "roomid" // this array's field name that links it to parent
)
)
)
)
); // $tree_arr
NOW CREATE OBJECT AND PROCESS INTO DESTINATION ARRAY
$c = new class_chain_filter();
$return_arr = $c->chain_filter($tree_arr);
print_r($return_arr);
... AND THE OUTPUT SHOULD LOOK LIKE ...
Array (
[0] => Array
(
[id] => 1
[name] => New World
[author] => anon
[resetfreq] => 3
[rooms] => Array
(
[0] => Array
(
[id] => 1
[areaid] => 1
[name] => Entrance
[description] => The air is humid here.
[exits] => Array
(
[0] => Array
(
[id] => 1
[roomid] => 1
[toroomid] => 2
[direction] => n
[description] => A Hall
[keyid] => 1
)
[1] => Array
(
[id] => 5
[roomid] => 1
[toroomid] => 3
[direction] => s
[description] => Entrance
[keyid] =>
)
)
)
[1] => Array
(
[id] => 2
[areaid] => 1
[name] => A Corridor
[description] => Seems nothing is really going on in this room. Bland tapestry and nothing worth really hanging around for. From the west comes the sound of people training. To the east you can hear people practicing skills and abilities.
[exits] => Array
(
[0] => Array
(
[id] => 2
[roomid] => 2
[toroomid] => 1
[direction] => s
[description] => A Corridor
[keyid] =>
)
[1] => Array
(
[id] => 7
[roomid] => 2
[toroomid] => 4
[direction] => e
[description] => Practice Room
[keyid] =>
)
[2] => Array
(
[id] => 9
[roomid] => 2
[toroomid] => 5
[direction] => w
[description] => Training Room
[keyid] =>
)
[3] => Array
(
[id] => 11
[roomid] => 2
[toroomid] => 8
[direction] => n
[description] => A Bend
[keyid] =>
)
)
)
)
)
)
and then you could just json_encode the array to turn it from a PHP array into a JSON string

Categories