How to send Blank Array when no data found? - php

I developed State->city->area wise selection in PHP.
All things works fine. But there is no data found in city there it removed city array.
I want to pass Empty city array to API response When no data found from database. How can I do this ?
My code look like this
if (isset($credentials->credentials->uid) && $credentials->credentials->uid != ""):
$mainArr = array();
$stateArr = array();
$state = $this->Data_model->Custome_query('SELECT mf_state_id, name, status FROM mf_state WHERE status = "A"');
foreach ($state as $s) {
$sArr = array();
$sArr = array(
'mf_state_id' => $s['mf_state_id'],
'name' => $s['name'],
'status' => $s['status']
);
$cityArr = array();
$city = $this->Data_model->Custome_query('SELECT mf_city_id, mf_state_id, name, status, active FROM mf_city WHERE status = "A" AND active = "S" AND mf_state_id = '.$s['mf_state_id']);
foreach ($city as $c) {
$cArr = array();
$cArr = array(
'mf_city_id' => $c['mf_city_id'],
'mf_state_id' => $c['mf_state_id'],
'name' => $c['name'],
'status' => $c['status'],
'active' => $c['active']
);
$areaArr = array();
$area = $this->Data_model->Custome_query('SELECT mf_area_id, mf_city_id, area, status FROM mf_area WHERE status = "A" AND mf_city_id = '.$c['mf_city_id']);
foreach ($area as $a) {
$aArr = array();
$aArr = array(
'mf_area_id' => $a['mf_area_id'],
'mf_city_id' => $a['mf_city_id'],
'area' => $a['area'],
'status' => $a['status'],
);
$areaArr[] = $aArr;
$cArr['area'] = $areaArr;
}
// print_r($cityArr);
$cityArr[] = $cArr;
$sArr['cities'] = $cityArr;
// print_r($sArr['cities']);
}
$stateArr[] = $sArr;
}
// print_r($sArr['cities']);
$mainArr = $stateArr;
echo str_replace("\/", "/", json_encode( ['res' => 0, 'msg' => 'Successfully got City Area data', 'data' => $mainArr, 'version' => $this->version,"qry"=>""]));
and response I am getting is look like this
{
"res": 0,
"msg": "Successfully got City Area data",
"data": [
{
"mf_state_id": "1",
"name": "Gujarat",
"status": "A",
"cities": [
{
"mf_city_id": "1",
"mf_state_id": "1",
"name": "Surat",
"status": "A",
"active": "S",
"area": [
{
"mf_area_id": "1",
"mf_city_id": "1",
"area": "Adajan",
"status": "A"
},
{
"mf_area_id": "2",
"mf_city_id": "1",
"area": "Bhatar",
"status": "A"
},
{
"mf_area_id": "3",
"mf_city_id": "1",
"area": "Dindoli",
"status": "A"
},
{
"mf_area_id": "4",
"mf_city_id": "1",
"area": "Kapodra",
"status": "A"
},
{
"mf_area_id": "5",
"mf_city_id": "1",
"area": "Mota Varachha",
"status": "A"
},
{
"mf_area_id": "6",
"mf_city_id": "1",
"area": "Nana Varachha",
"status": "A"
},
{
"mf_area_id": "7",
"mf_city_id": "1",
"area": "Palanpur Patiya",
"status": "A"
},
{
"mf_area_id": "8",
"mf_city_id": "1",
"area": "Parvat Patiya",
"status": "A"
},
{
"mf_area_id": "9",
"mf_city_id": "1",
"area": "Udhna",
"status": "A"
},
{
"mf_area_id": "10",
"mf_city_id": "1",
"area": "Athwa",
"status": "A"
},
{
"mf_area_id": "11",
"mf_city_id": "1",
"area": "Bhatha",
"status": "A"
},
{
"mf_area_id": "12",
"mf_city_id": "1",
"area": "Ghoddod Road",
"status": "A"
},
{
"mf_area_id": "13",
"mf_city_id": "1",
"area": "Katargam",
"status": "A"
},
{
"mf_area_id": "14",
"mf_city_id": "1",
"area": "Pandesara",
"status": "A"
},
{
"mf_area_id": "15",
"mf_city_id": "1",
"area": "Piplod",
"status": "A"
},
{
"mf_area_id": "16",
"mf_city_id": "1",
"area": "Vesu",
"status": "A"
},
{
"mf_area_id": "17",
"mf_city_id": "1",
"area": "Citylight",
"status": "A"
},
{
"mf_area_id": "18",
"mf_city_id": "1",
"area": "Jahangirpura",
"status": "A"
},
{
"mf_area_id": "19",
"mf_city_id": "1",
"area": "Pal",
"status": "A"
},
{
"mf_area_id": "20",
"mf_city_id": "1",
"area": "Parle Point",
"status": "A"
},
{
"mf_area_id": "21",
"mf_city_id": "1",
"area": "Rander",
"status": "A"
},
{
"mf_area_id": "28",
"mf_city_id": "1",
"area": "Zampa Bazaar",
"status": "A"
},
{
"mf_area_id": "40",
"mf_city_id": "1",
"area": "Rander Road",
"status": "A"
},
{
"mf_area_id": "43",
"mf_city_id": "1",
"area": "Varachha Road",
"status": "A"
},
{
"mf_area_id": "58",
"mf_city_id": "1",
"area": "Palanpur Gam",
"status": "A"
},
{
"mf_area_id": "63",
"mf_city_id": "1",
"area": "Palanpur Jakatnaka",
"status": "A"
},
{
"mf_area_id": "92",
"mf_city_id": "1",
"area": "New Causeway Road",
"status": "A"
}
]
}
]
},
{
"mf_state_id": "2",
"name": "Maharastra",
"status": "A"
}
],
"version": "1.0",
"qry": ""
}
In last state Maharastra there is no city in data base.
but it should return city array blank.
I want response look like this. City array should come null array when Data not found
{
"res": 0,
"msg": "Successfully got City Area data",
"data": [
{
"mf_state_id": "1",
"name": "Gujarat",
"status": "A",
"cities": [
{
"mf_city_id": "1",
"mf_state_id": "1",
"name": "Surat",
"status": "A",
"active": "S",
"area": [
{
"mf_area_id": "1",
"mf_city_id": "1",
"area": "Adajan",
"status": "A"
},
{
"mf_area_id": "2",
"mf_city_id": "1",
"area": "Bhatar",
"status": "A"
},
{
"mf_area_id": "3",
"mf_city_id": "1",
"area": "Dindoli",
"status": "A"
},
{
"mf_area_id": "4",
"mf_city_id": "1",
"area": "Kapodra",
"status": "A"
},
{
"mf_area_id": "5",
"mf_city_id": "1",
"area": "Mota Varachha",
"status": "A"
},
{
"mf_area_id": "6",
"mf_city_id": "1",
"area": "Nana Varachha",
"status": "A"
},
{
"mf_area_id": "7",
"mf_city_id": "1",
"area": "Palanpur Patiya",
"status": "A"
},
{
"mf_area_id": "8",
"mf_city_id": "1",
"area": "Parvat Patiya",
"status": "A"
},
{
"mf_area_id": "9",
"mf_city_id": "1",
"area": "Udhna",
"status": "A"
},
{
"mf_area_id": "10",
"mf_city_id": "1",
"area": "Athwa",
"status": "A"
},
{
"mf_area_id": "11",
"mf_city_id": "1",
"area": "Bhatha",
"status": "A"
},
{
"mf_area_id": "12",
"mf_city_id": "1",
"area": "Ghoddod Road",
"status": "A"
},
{
"mf_area_id": "13",
"mf_city_id": "1",
"area": "Katargam",
"status": "A"
},
{
"mf_area_id": "14",
"mf_city_id": "1",
"area": "Pandesara",
"status": "A"
},
{
"mf_area_id": "15",
"mf_city_id": "1",
"area": "Piplod",
"status": "A"
},
{
"mf_area_id": "16",
"mf_city_id": "1",
"area": "Vesu",
"status": "A"
},
{
"mf_area_id": "17",
"mf_city_id": "1",
"area": "Citylight",
"status": "A"
},
{
"mf_area_id": "18",
"mf_city_id": "1",
"area": "Jahangirpura",
"status": "A"
},
{
"mf_area_id": "19",
"mf_city_id": "1",
"area": "Pal",
"status": "A"
},
{
"mf_area_id": "20",
"mf_city_id": "1",
"area": "Parle Point",
"status": "A"
},
{
"mf_area_id": "21",
"mf_city_id": "1",
"area": "Rander",
"status": "A"
},
{
"mf_area_id": "28",
"mf_city_id": "1",
"area": "Zampa Bazaar",
"status": "A"
},
{
"mf_area_id": "40",
"mf_city_id": "1",
"area": "Rander Road",
"status": "A"
},
{
"mf_area_id": "43",
"mf_city_id": "1",
"area": "Varachha Road",
"status": "A"
},
{
"mf_area_id": "58",
"mf_city_id": "1",
"area": "Palanpur Gam",
"status": "A"
},
{
"mf_area_id": "63",
"mf_city_id": "1",
"area": "Palanpur Jakatnaka",
"status": "A"
},
{
"mf_area_id": "92",
"mf_city_id": "1",
"area": "New Causeway Road",
"status": "A"
}
]
}
]
},
{
"mf_state_id": "2",
"name": "Maharastra",
"status": "A",
"cities": []
}
],
"version": "1.0",
"qry": ""
}

You should initialize the $sArr with cities key as empty array. If the cities are then found of the state, the cities key will be overwritten in the loop else you will get empty values.
$sArr = array();
$sArr = array(
'mf_state_id' => $s['mf_state_id'],
'name' => $s['name'],
'status' => $s['status'],
'cities' => array(), //Initialize with empty array here.
);

Try this, If state have no cities or empty then other code does not execute.
if(count($city)>0){
foreach ($city as $c) {
$cArr = array(
'mf_city_id' => $c['mf_city_id'],
'mf_state_id' => $c['mf_state_id'],
'name' => $c['name'],
'status' => $c['status'],
'active' => $c['active']
);
}
}else{
$cArr = array();
}

Related

creating json file from database

I need to create this json in the following format
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "Product 1",
"quantity": "1",
"price": "5.00"
},
{
"productName": "Product 2",
"quantity": "2",
"price": "24.00"
},
{
"productName": "Product 3",
"quantity": "1",
"price": "6.50"
}
]
},
{
"orderId": "2",
"orderDate": "2/06/2021",
"products": [
{
"productName": "Product 1",
"quantity": "1",
"price": "3.00"
},
{
"productName": "Product 2",
"quantity": "1",
"price": "11.50"
}
]
},
{
"orderId": "3",
"orderDate": "03/05/2021",
"products": [
{
"productName": "Product 1",
"quantity": "1",
"price": "3.00"
},
{
"productName": "Product 2",
"quantity": "1",
"price": "11.50"
}
]
}
]
}
This is my code that I use to retrive the information from the database
$stmt = $con->prepare("SELECT OrderID, OrderDate, ProductName, ProductQty, ProductPrice FROM Orders where CustomerID = ?");
$stmt->bind_param("s", $CustomerID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($OrderID, $OrderDate, $ProductName, $ProductQty, $ProductPrice);
while($stmt->fetch()) {
$message[] = array(
"status" => true,
"message" => "",
"orders" => array(
array(
"orderId" => "$OrderID",
"orderDate" => "$OrderDate",
"products" => array(
array(
"productName" => "$ProductName",
"quantity" => "$ProductQty",
"price" => "$ProductPrice"
),
)
)
)
);
}
$json = $message;
header('content-type: application/json');
echo json_encode($json);
This is how the information from the database displays. I do not know how to show the information about the products correctly. Can anyone show me how to do it in the format that I require in php? Thanks in advance for any help.
[
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "620",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "240",
"quantity": "1",
"price": "5.00"
},
{
"productName": "270",
"quantity": "1",
"price": "10.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "30",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "280",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "610",
"quantity": "1",
"price": "5.00"
}
]
}
]
}
]
You are repeating the orders structure which you shouldn't. That's why you get the wrong structure. This is what you should do instead (your code, modified):
// specify your return response array only once
$message = array(
"status" => true,
"message" => "",
"orders" => array();
);
$stmt = $con->prepare("SELECT OrderID, OrderDate, ProductName, ProductQty, ProductPrice FROM Orders where CustomerID = ?");
$stmt->bind_param("s", $CustomerID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($OrderID, $OrderDate, $ProductName, $ProductQty, $ProductPrice);
while($stmt->fetch()) {
// and fill its "orders" member with your orders list
$message["orders"][] = array(
"orderId" => "$OrderID",
"orderDate" => "$OrderDate",
"products" => array(
array(
"productName" => "$ProductName",
"quantity" => "$ProductQty",
"price" => "$ProductPrice"
),
)
);
}
$json = $message;
header('content-type: application/json');
echo json_encode($json);
You can try like below
const data = [
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "620",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "240",
"quantity": "1",
"price": "5.00"
},
{
"productName": "270",
"quantity": "1",
"price": "10.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "30",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "280",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "610",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": false,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "800",
"quantity": "50",
"price": "5.00"
}
]
}
]
},
{
"status": false,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "1800",
"quantity": "50",
"price": "5.00"
}
]
}
]
}
];
const resutl = data.reduce((acc, cur) => {
const key = cur.status ? "successItems" : "failureItems";
if (acc[key]) {
return {
...acc,
[key]: {
status: cur.status,
messgae: '',
orders: [
...acc[key].orders,
...cur.orders
]
}
}
} else {
return {
...acc,
[key]: {
status: cur.status,
messgae: '',
orders: [
...cur.orders
]
}
}
}
}, {});
console.log('resutl', resutl);
console.log('resutl', Object.values(resutl));

how to parse the json using php? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
{
"result": "success",
"clientid": "1",
"serviceid": null,
"pid": null,
"domain": null,
"totalresults": "2",
"startnumber": 0,
"numreturned": 2,
"products": {
"product": [
{
"id": "1",
"clientid": "1",
"orderid": "1",
"pid": "1",
"regdate": "2015-01-01",
"name": "Starter",
"translated_name": "Starter",
"groupname": "Shared Hosting",
"translated_groupname": "Shared Hosting",
"domain": "demodomain.com",
"dedicatedip": "",
"serverid": "1",
"servername": "Saturn",
"serverip": "1.2.3.4",
"serverhostname": "saturn.example.com",
"suspensionreason": "",
"firstpaymentamount": "12.95",
"recurringamount": "12.95",
"paymentmethod": "authorize",
"paymentmethodname": "Credit Card",
"billingcycle": "Monthly",
"nextduedate": "2016-11-25",
"status": "Terminated",
"username": "demodoma",
"password": "xxxxxxxx",
"subscriptionid": "",
"promoid": "0",
"overideautosuspend": "",
"overidesuspenduntil": "0000-00-00",
"ns1": "",
"ns2": "",
"assignedips": "",
"notes": "",
"diskusage": "0",
"disklimit": "0",
"bwusage": "0",
"bwlimit": "0",
"lastupdate": "0000-00-00 00:00:00",
"customfields": {
"customfield": []
},
"configoptions": {
"configoption": []
}
},
{
"id": "2",
"clientid": "1",
"orderid": "2",
"pid": "3",
"regdate": "2015-05-20",
"name": "Plus",
"translated_name": "Plus",
"groupname": "Shared Hosting",
"translated_groupname": "Shared Hosting",
"domain": "demodomain2.net",
"dedicatedip": "",
"serverid": "2",
"servername": "Pluto",
"serverip": "2.3.4.5",
"serverhostname": "pluto.example.com",
"suspensionreason": "",
"firstpaymentamount": "24.95",
"recurringamount": "24.95",
"paymentmethod": "paypal",
"paymentmethodname": "PayPal",
"billingcycle": "Monthly",
"nextduedate": "2017-01-20",
"status": "Active",
"username": "demodom2",
"password": "xxxxxxxx",
"subscriptionid": "",
"promoid": "0",
"overideautosuspend": "",
"overidesuspenduntil": "0000-00-00",
"ns1": "",
"ns2": "",
"assignedips": "",
"notes": "",
"diskusage": "0",
"disklimit": "0",
"bwusage": "0",
"bwlimit": "0",
"lastupdate": "0000-00-00 00:00:00",
"customfields": {
"customfield": []
},
"configoptions": {
"configoption": [
{
"id": "1",
"option": "Sample Config Option",
"type": "dropdown",
"value": "Selected option value"
}
]
}
}
]
}
}
How can i parse the product details from json
You can use json decode function of php to make object then fetch data from object.
$data = 'write your json response here';
$return = json_decode($data);
print_r($return);
echo $return->result;

Sorting only a part of object/array in PHP

I've been struggling around this for a while now and can't seem to get the right algorithm.
What I want is to sort this:
$variable = '{
"0": {
"id": "0",
"code": "main_colour",
"label": "Main Colour",
"options": [{
"id": "825",
"label": "White",
"products": ["1", "2", "3"]
}, {
"id": "840",
"label": "Cream",
"products": ["3", "4", "5"]
}],
"position": "0"
},
"2": {
"id": "0",
"code": "size",
"label": "Size",
"options": [{
"id": "825",
"label": "S",
"products": ["1", "2", "3"]
}, {
"id": "840",
"label": "M",
"products": ["3", "4", "5"]
}],
"position": "0"
}
}';
And the output would be
$variable = '{
"0": {
"id": "0",
"code": "main_colour",
"label": "Main Colour",
"options": [{
"id": "840",
"label": "Cream",
"products": ["3", "4", "5"]
},{
"id": "825",
"label": "White",
"products": ["1", "2", "3"]
}],
"position": "0"
},
"2": {
"id": "0",
"code": "size",
"label": "Size",
"options": [{
"id": "840",
"label": "M",
"products": ["3", "4", "5"]
}, {
"id": "825",
"label": "S",
"products": ["1", "2", "3"]
}],
"position": "0"
}
}';
So basically it should be sorted using the label inside the "options" without affecting the other fields. I've been trying usort and tried different algorithms but to no avail.
Current code that sorts only the outside "label" and not the inner label:
function optionsSort($a, $b) {
return strcmp($a['options'][0]['label'], $b['options'][0]['options']['label']);
}
usort($variable, "optionsSort"));
Here's the code:
// your array
$variable = '{
"0": {
"id": "0",
"code": "main_colour",
"label": "Main Colour",
"options": [{
"id": "825",
"label": "White",
"products": ["1", "2", "3"]
}, {
"id": "840",
"label": "Cream",
"products": ["3", "4", "5"]
}],
"position": "0"
},
"2": {
"id": "0",
"code": "size",
"label": "Size",
"options": [{
"id": "825",
"label": "S",
"products": ["1", "2", "3"]
}, {
"id": "840",
"label": "M",
"products": ["3", "4", "5"]
}],
"position": "0"
}
}';
$a = json_decode($variable);
foreach ($a as $item) {
// sorting function
usort($item->options, function($a, $b) { return strcmp($a->label, $b->label); });
}

Get all options for configurable product Magento 2.0 REST Api

When i call this API,
{{base_url}}index.php/rest/V1/configurable-products/:sku/options/all
I am getting a response like this,
[
{
"id": 9,
"attribute_id": "93",
"label": "Color",
"position": 0,
"values": [
{
"value_index": 15
},
{
"value_index": 16
},
{
"value_index": 17
}
],
"product_id": 19
},
{
"id": 10,
"attribute_id": "176",
"label": "side",
"position": 1,
"values": [
{
"value_index": 18
},
{
"value_index": 19
}
],
"product_id": 19
}
]
But i want label for all these value_indexes.Could i get all these values in a single request
There is an pi for getting all the labels,
{{base_url}}/index.php/rest/V1/products/attributes/:attribute_id/options
Ex:
{{base_url}}/index.php/rest/V1/products/attributes/93/options
will return
[
{
"label": " ",
"value": ""
},
{
"label": "green",
"value": "12"
},
{
"label": "yellow",
"value": "13"
},
{
"label": "red",
"value": "14"
}
]
You can use this endpoint to fetch multiple attribute sets in a single request
/rest/V1/products/attributes
example:
{domain}/rest/V1/products/attributes?search_criteria[filter_groups][0][filters][0][field]=attribute_id&search_criteria[filter_groups][0][filters][0][value]=93,138&search_criteria[filter_groups][0][filters][0][condition_type]=in
response:
"items": [
{
"is_wysiwyg_enabled": false,
"is_html_allowed_on_front": false,
"used_for_sort_by": false,
"is_filterable": true,
"is_filterable_in_search": false,
"is_used_in_grid": true,
"is_visible_in_grid": false,
"is_filterable_in_grid": true,
"position": 0,
"apply_to": [
"simple",
"virtual",
"configurable"
],
"is_searchable": "1",
"is_visible_in_advanced_search": "1",
"is_comparable": "1",
"is_used_for_promo_rules": "0",
"is_visible_on_front": "0",
"used_in_product_listing": "0",
"is_visible": true,
"scope": "global",
"attribute_id": 93,
"attribute_code": "color",
"frontend_input": "select",
"entity_type_id": "4",
"is_required": false,
"options": [
{
"label": " ",
"value": ""
},
{
"label": "blue",
"value": "8"
},
{
"label": "red",
"value": "9"
},
{
"label": "black",
"value": "10"
},
{
"label": "white",
"value": "11"
}
],
"is_user_defined": true,
"default_frontend_label": "Color",
"frontend_labels": [],
"backend_type": "int",
"source_model": "Magento\\Eav\\Model\\Entity\\Attribute\\Source\\Table",
"default_value": "",
"is_unique": "0",
"validation_rules": []
},
{
"is_wysiwyg_enabled": false,
"is_html_allowed_on_front": true,
"used_for_sort_by": false,
"is_filterable": false,
"is_filterable_in_search": false,
"is_used_in_grid": true,
"is_visible_in_grid": true,
"is_filterable_in_grid": true,
"position": 0,
"apply_to": [],
"is_searchable": "0",
"is_visible_in_advanced_search": "0",
"is_comparable": "0",
"is_used_for_promo_rules": "0",
"is_visible_on_front": "0",
"used_in_product_listing": "0",
"is_visible": true,
"scope": "global",
"attribute_id": 138,
"attribute_code": "simple_size",
"frontend_input": "select",
"entity_type_id": "4",
"is_required": true,
"options": [
{
"label": " ",
"value": ""
},
{
"label": "small",
"value": "12"
},
{
"label": "medium",
"value": "13"
},
{
"label": "large",
"value": "14"
}
],
"is_user_defined": true,
"default_frontend_label": "simple_size",
"frontend_labels": [
{
"store_id": 1,
"label": "Size"
}
],
"backend_type": "int",
"source_model": "Magento\\Eav\\Model\\Entity\\Attribute\\Source\\Table",
"default_value": "",
"is_unique": "0",
"validation_rules": []
}
],
"search_criteria": {
"filter_groups": [
{
"filters": [
{
"field": "attribute_id",
"value": "93,138",
"condition_type": "in"
}
]
}
]
},
"total_count": 2
}

php JSON data structure for angular app

I am trying to format the a mysql response into a array of objects so that Angular can easily traverse the data.
mysql result:
[{
"FIAccountsID": "99",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "1"
},
{
"FIAccountsID": "99",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "2"
},
{
"FIAccountsID": "100",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "1"
},
{
"FIAccountsID": "100",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "2"
},
{
"FIAccountsID": "101",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "1"
},
{
"FIAccountsID": "101",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "2"
},
{
"FIAccountsID": "102",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "1"
},
{
"FIAccountsID": "102",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "2"
},
{
"FIAccountsID": "103",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "1"
},
{
"FIAccountsID": "103",
"AccountName": "",
"AccountCustomName": "Brothers",
"AccountNumber": "99-123123123",
"AccountTypeName": "IRA",
"FinancialInstName": "Testes",
"FinancialInstID": "9",
"UserID": "1",
"ofxStatusCode": "500",
"UserAccountID": "09128-vc-12",
"FirstName": "Someones",
"LastName": "Name",
"Status": "2"
}......
here it the PHP:
while($row = mysqli_fetch_assoc($result))
{
$uid = $row['UserID'];
$name = $row['FirstName'].' '.$row['LastName'];
$fiid = $row['FinancialInstID'];
$fi = $row['FinancialInstName'];
$acctID = $row['FIAccountsID'];
$rows[$uid]['name'] = $name;
$rows[$uid]['uid'] = $uid;
$rows[$uid]['fi'][$fiid]['name'] = $fi;
$rows[$uid]['fi'][$fiid]['acct'][$acctID]['name'] = $row['AccountCustomName'];
}
print json_encode($rows);
this is what i get:
{
"1": {
"name": "Some Name",
"uid": "1",
"fi": {
"9": {
"name": "Testes",
"accts": {
"99": {
"name": "name 1"
},
"100": {
"name": "name 2"
},
"103": {
"name": "name 3"
}
}
}
}
},
"2": {
"name": "Another Name",
"uid": "2",
"fi": {
"7": {
"name": "Trevor's Brokerage House",
"accts": {
"1": {
"name": "Sally's 401k Account"
},
"2": {
"name": "retirement"
},
"3": {
"name": "Some other account"
..........
desired result:
[
{
"users": [
{
"name": "Some Name",
"uid": "1",
"fi": [
{
"name": "Testes",
"acct": [
{
"name": "name 1"
},
{
"name": "name 2"
},
{
"name": "name 3"
}
]
}
]
},
{
"name": "Another Name",
"uid": "2",
"fi": [
{
"name": "Trevor's Brokerage House",
"acct": [
{
"name": "Sally's 401k Account"
},
{
"name": "retirement"
},
{
"name": "Some other account"
..........
I want to know how to have the data structure without the unique keys prefixing the nested arrays
The thing is that if you define keys, json_encode will read them. If you don't want keys, declare the array without them. So, what you need to do is to structure your array according to you desired output.
But the way your data is arranged make it somewhat hard to format it properly. The solution I can see is to do what you're already doing:
while($row = mysqli_fetch_assoc($result))
{
$uid = $row['UserID'];
$name = $row['FirstName'].' '.$row['LastName'];
$fiid = $row['FinancialInstID'];
$fi = $row['FinancialInstName'];
$acctID = $row['FIAccountsID'];
$rows[$uid]['name'] = $name;
$rows[$uid]['uid'] = $uid;
$rows[$uid]['fi'][$fiid]['name'] = $fi;
$rows[$uid]['fi'][$fiid]['acct'][$acctID]['name'] = $row['AccountCustomName'];
}
But then you revisit the array and remove all the keys using array_values:
foreach ($rows as $uid => $data)
{
foreach ($data['fi'] as $fiid => $fi)
{
$rows[$uid]['fi'][$fiid]['acct'] = array_values($fi['acct']);
}
$rows[$uid]['fi'] = array_values($rows[$uid]['fi']);
}
// Here you format the outer array:
$rows = array(array('users' => array_values($rows)));
Which gives a result like this:
[
{
"users": [
{
"name": "Someones Name",
"uid": "1",
"fi": [
{
"name": "Testes",
"acct": [
{
"name": "Brothers"
},
{
"name": "Brothers"
},
{
"name": "Brothers"
},
{
"name": "Brothers"
},
{
"name": "Brothers"
}
]
}
]
},
{
"name": "Someones Name",
"uid": "2",
"fi": [
{
"name": "Testes",
"acct": [
{
"name": "Brothers"
},
{
"name": "Brothers"
}
]
}
]
}
]
}
]

Categories