Multidimensional array combines same key and value into already defined array element - php

I new to php, getting mysql results storing json but its not gettng coorect format what I want.
Pease check below code
$sql = "select * from en_providers where providerEmailAddress='" . $email . "' and providerPW='" . $password . "'";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($connection));
if (mysqli_num_rows($result) > 0) {
$resultArray = array();
while ($row = mysqli_fetch_assoc($result)) {
$providerID = $row['providerID'];
$resultArray['providers'] = $row;
$resultArray['providers']['providerIDActivities'] = unserialize($row['providerIDActivities']);
$resultArray['providers']['providerIDBodies'] = unserialize($row['providerIDBodies']);
$resultArray['providers']['providerIDOthers'] = unserialize($row['providerIDOthers']);
$sql1 = "select * from en_venues where providerID = $providerID ";
$result1 = mysqli_query($con, $sql1) or die("Error in Selecting " . mysqli_error($connection));
$i = $j = $l = $x = $m = 0;
while ($row1[] = mysqli_fetch_assoc($result1)) {
//$resultArray['venues'][]['venueIDFacilities'] = unserialize($row1[$j++]['venueIDFacilities']);
$venueID = $row1[$j++]['venueID'];
$k = 0;
$venueFacilities = unserialize($row1[$i++]['venueIDFacilities']);
$resultArray[$x++]['venues']['venueIDFacilities'] = $venueFacilities;
//$resultArray['venues'][$x++]['venueID'] = $venueID;
$resultArray['venues'] = $row1;
//echo json_encode($resultArray);
echo json_encode($resultArray);
}
}
Output is:
{
0: {
"venues": {
"venueIDFacilities": [
"1",
"2",
"3"
],
}
},
1: {
"venues": {
"venueIDFacilities": [
"4",
"7"
],
}
}
},
"providers": {
"providerIDActivities": [
"218",
"219"
],
"providerIDSports": "a:1:{i:0;i:82;}",
"providerIDBodies": [
"112"
],
},
venues": {
0: {
"venueID": "9",
"providerID": "2"
},
1: {
"venueID": "238",
"providerID": "2",
"venueActive": "yes"
}
}
But I need those VenueFailities to be in respective venues but result is getting outside. How can I append those values into venues?
I am trying for one day with different ways but it's not getting correct format.
Output I want:
"providers": {
"providerIDActivities": [
"218",
"219"
],
"providerIDSports": "a:1:{i:0;i:82;}",
"providerIDBodies": [
"112"
],
},
venues": {
0: {
"venueID": "9",
"providerID": "2",
"venueIDFacilities": [
"4",
"7"
]
},
1: {
"venueID": "238",
"providerID": "2",
venueIDFacilities": [
"4",
"7"
]
}
}

This line
$resultArray[$x++]['venues']['venueIDFacilities'] = $venueFacilities;
should be
$resultArray['venues'][$x++]['venueIDFacilities'] = $venueFacilities;

Related

Array format inside JSON response using php

Send data from PHP platform to Android platform using "REST" API call .
I am facing issue in forming exact structure (how to structure" array inside json) .
I am new to REST API (REQUEST and RESPONSE)
please help me to solve this problem
The php code is as below:
case 'question':
$lesson = $_POST['lesson'];
$chapter = $_POST['chapter'];
if(!isset($lesson) || !isset($chapter)){
$response['error'] = true;
$response['message'] = 'key and values is empty (or) wrong';
http_response_code(404);
}
//for login we need the username and password
if(isTheseParametersAvailable(array('lesson','chapter'))){
//getting values
$lesson = $_POST['lesson'];
$chapter = $_POST['chapter'];
//creating the query
$query = "SELECT que_desc,option1,option2,option3,option4,true_ans FROM question WHERE lesson = '".$lesson."' AND chapter = '".$chapter."' ";
$result = mysqli_query($conn, $query);
// $user =array();
$questions =array();
$q = array();
$question = array();
$options = array();
$i=1;
//$j=0;
while($row = mysqli_fetch_assoc($result)){
$q["q".$i]['question'] = $row['que_desc'];
$q["q".$i]['option'][1] = $row['option1'];
$q["q".$i]['option'][2] = $row['option2'];
$q["q".$i]['option'][3] = $row['option3'];
$q["q".$i]['option'][4] = $row['option4'];
$q["q".$i]['answer'] = $row['true_ans'];
$i++;
}
$questions['questions'] = $q;
header('Content-Type: application/json');
echo json_encode($questions , JSON_FORCE_OBJECT);
exit;
}
break;
Below Code with "Structure Error"
{
"questions": {
"q1": {
"question": "question 1",
"option": {
"1": "option1",
"2": "option2",
"3": "option3",
"4": "option4"
},
"answer": "4"
},
"q2": {
"question": "question2",
"option": {
"1": "option1",
"2": "option2",
"3": "option3",
"4": "option4"
},
"answer": "2"
}
}
}
Expected Answer
{
"questions": {
"q1": {
"question": "question1",
"options": [
"option1",
"option2",
"option3",
"option4"
],
"answer": "option1"
},
"q2": {
"question": "question 2",
"options": [
"option1",
"option2",
"option3",
"option4"
],
"answer": "option2"
}
}
}
thanks in Advance .
Try using array :
while($row = mysqli_fetch_assoc($result)){
$q["q".$i]['question'] = $row['que_desc'];
$q["q".$i]['option'] = array($row['option1'], $row['option2'], $row['option3'], $row['option4']);
$q["q".$i]['answer'] = $row['true_ans'];
$i++;
}

Generate JSON Array from PHP SQL Loop

I need to generate the following JSON from a PHP loop and SQL DB but I'm having trouble:
[
{
"ItemName": "Websites1",
"Websites1": [
{
"0": "1",
"ID": "1",
"1": "Essential",
"WebsiteName": "Essential 1",
"2": "EI",
"WebsiteCode": "EI"
},
{
"0": "2",
"ID": "2",
"1": "Icon Ibiza",
"WebsiteName": "Icon 1",
"2": "IC",
"WebsiteCode": "IC"
},
{
"0": "3",
"ID": "3",
"1": "So Ibiza",
"WebsiteName": "So 1",
"2": "SO",
"WebsiteCode": "SO"
}
]
},
{
"ItemName": "Websites2",
"Websites2": [
{
"0": "1",
"ID": "1",
"1": "Essential Ibiza",
"WebsiteName": "Essential 2",
"2": "EI",
"WebsiteCode": "EI"
},
{
"0": "2",
"ID": "2",
"1": "Icon Ibiza",
"WebsiteName": "Icon 2",
"2": "IC",
"WebsiteCode": "IC"
},
{
"0": "3",
"ID": "3",
"1": "So Ibiza",
"WebsiteName": "So 2",
"2": "SO",
"WebsiteCode": "SO"
}
]
}
]
I have the relevant data being returned from the DB into PHP fine but I can't work out how to generate the relevant key value pairs and nesting using PHP loops. The code I have so far is:
$this->db->sql = "SELECT ID AS ID, WebsiteName AS SelectText, WebsiteCode AS SelectValue FROM Banners_Websites ORDER BY WebsiteName";
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$response = array();
$json = array();
while ($row = $this->db->row_read($rs)) {
$json["ID"] = $row["ID"];
$json["SelectText"] = $row["SelectText"];
$json["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites1"] = $json;
}
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$json2 = array();
while ($row = $this->db->row_read($rs)) {
$json2["ID"] = $row["ID"];
$json2["SelectText"] = $row["SelectText"];
$json2["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites2"] = $json2;
}
return '[' . json_encode($response) . ']';
I'm obviously doing something very wrong as I only end up with one row for each query. The key value pairs are being overwritten with each loop. Also the nesting isn't correct. Sorry for such a dumb question but I've been trying to figure this out from info online and am stuck.
Thanks,
Noon.
EDIT - Managed to fix this using the annswer provided by Anushil Nandan below but the PHP needed a few extra tweaks to get the required format as folows:
// -----------------------------------------------------------------------------------------------
// BANNERMANGEMENTFORM
function bannerManagementJson($JsonItem) {
$this->db->connect();
$response = array();
//Generate Websites drop-down
$SqlStr = "SELECT WebsiteName AS SelectText, WebsiteCode AS SelectValue FROM Banners_Websites ORDER BY WebsiteName";
$response[] = $this->retrieveFormElementJson($SqlStr,'Websites',1);
//Generate Clients drop-down
$SqlStr = "SELECT ClientName AS SelectText, ID AS SelectValue FROM Banners_BannerClients ORDER BY ClientName";
$response[] = $this->retrieveFormElementJson($SqlStr,'Clients',2);
return json_encode($response);
}
// -----------------------------------------------------------------------------------------------
// RETRIEVEFORMELEMENTJSON
function retrieveFormElementJson($SqlStr,$ElementName,$SelectListNo) {
$this->db->sql = $SqlStr;
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$json = array();
while ($row = $this->db->row_read($rs)) {
$json[] = $row;
}
$arrayResponse = array("ItemName"=>$ElementName, "SelectList" . $SelectListNo=>$json);
}
return $arrayResponse;
}
your array is being overridden every time it's entering while loop
try:
$json1[] = array();
$json2[] = array();
$this->db->sql = "SELECT ID AS ID, WebsiteName AS SelectText, WebsiteCode AS SelectValue FROM Banners_Websites ORDER BY WebsiteName";
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$response = array();
$json[] = array();
while ($row = $this->db->row_read($rs)) {
$json[]["ID"] = $row["ID"];
$json[]["SelectText"] = $row["SelectText"];
$json[]["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites1"] = $json;
}
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$json2[] = array();
while ($row = $this->db->row_read($rs)) {
$json2[]["ID"] = $row["ID"];
$json2[]["SelectText"] = $row["SelectText"];
$json2[]["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites2"] = $json2;
}
return '[' . json_encode($response) . ']';

How to place one array inside another?

I've researched how to add an array inside another array but the result wasn't quite what I expected. I tried using 'array_push' and 'array_merge' but neither one solved my problem. Here's the code I have so far:
else if ($_GET['type'] == "listaJogos") {
//echo 'Tipo de operação: ' . $_GET['type'] . '<br>';
$campeonato_id = $_GET['campeonato'];
//Query que retorna a NOME_TIME, ID, DATA_HORA, TB_COTACAO_ID
$query = "SELECT GROUP_CONCAT(timee.nome_time ORDER BY timee.nome_time SEPARATOR ' X ') AS nome_time,
partida.id, partida.data_hora, partida.tb_cotacao_id
FROM tb_partida AS partida, tb_time AS timee, tb_partida_time AS partidaTime
WHERE (partida.id = tb_partida_id && timee.id = tb_time_id)
AND (partida.flag_ativo = 1 AND partida.flag_cancelado <> 1 AND partida.flag_finalizado <> 1)
AND partida.tb_campeonato_id = $campeonato_id
GROUP BY partida.id";
$query2 = "SELECT * FROM `tb_cotacao` WHERE `id` = ";
$result = mysqli_query($link, $query);
//--------------------------------------------------------------------------
while ($reg = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$registros[] = array('partida' => $reg);
$result2 = mysqli_query($link, $query2 . $reg['tb_cotacao_id']);
//$registros[] = array('partida' => mysqli_fetch_array($result2, MYSQLI_ASSOC));
array_push($registros, mysqli_fetch_array($result2, MYSQLI_ASSOC));
}
$saida = json_encode(array('json' => $registros));
echo $saida;
}
The code above gives me the output below:
"json": [
{
"partida": {
"nome_time": "Acreano\r X Flamengo\r",
"id": "4",
"data_hora": "2016-09-03 14:00:00",
"tb_cotacao_id": "4"
}
},
{
"id": "4",
"casa": "1.23",
"empate": "2.13",
"fora": "1.23",
"gol_meio": "6.00",
"mais_2gm": "7.00",
"menos_3gm": "7.67",
"ambas_marcam": "0.00",
"casa_empate": "6.00",
"fora_empate": "7.67",
"casa_marca": "6.00",
"fora_marca": "76.00",
"casa_ou_fora": "76.00",
"casavence_foramarca": "76.00",
"foravence_casamarca": "7.00",
"casavence_zero": "67.00",
"foravence_zero": "67.00"
}]
What I need is the array I'm trying to push to be inside 'partida', like this:
"json": [
{
"partida": {
"nome_time": "Acreano\r X Flamengo\r",
"id": "4",
"data_hora": "2016-09-03 14:00:00",
"tb_cotacao_id": "4"
"cotacoes": {
"id": "4",
"casa": "1.23",
"empate": "2.13",
"fora": "1.23",
"gol_meio": "6.00",
"mais_2gm": "7.00",
"menos_3gm": "7.67",
"ambas_marcam": "0.00",
"casa_empate": "6.00",
"fora_empate": "7.67",
"casa_marca": "6.00",
"fora_marca": "76.00",
"casa_ou_fora": "76.00",
"casavence_foramarca": "76.00",
"foravence_casamarca": "7.00",
"casavence_zero": "67.00",
"foravence_zero": "67.00"
}
}
}]
I'd really appreciate if someone can give me a hand with this.
array_push($registros[0]['partida'], mysqli_fetch_array($result2, MYSQLI_ASSOC));
use this
modify your 3rd line from last

Using PHP multidimensional arrays to convert MySQL to JSON

Here's my table structure.
I'm trying to convert MySQL to nested JSON, but am having trouble figuring out how to build the multidimensional array in PHP.
The result I want is similar to this:
[
{
"school_name": "School's Name",
"terms": [
{
"term_name":"FALL 2013",
"departments": [
{
"department_name":"MANAGEMENT INFO SYSTEMS",
"department_code":"MIS",
"courses": [
{
"course_code":"3343",
"course_name":"ADVANCED SPREADSHEET APPLICATIONS",
"sections": [
{
"section_code":"18038",
"unique_id": "mx00fdskljdsfkl"
},
{
"section_code":"18037",
"unique_id": "mxsajkldfk57"
}
]
},
{
"course_code":"4370",
"course_name":"ADVANCED TOPICS IN INFORMATION SYSTEMS",
"sections": [
{
"section_code":"18052",
"unique_id": "mx0ljjklab57"
}
]
}
]
}
]
}
]
}
]
The PHP I'm using:
$query = "SELECT school_name, term_name, department_name, department_code, course_code, course_name, section_code, magento_course_id
FROM schools INNER JOIN term_names ON schools.id=term_names.school_id INNER JOIN departments ON schools.id=departments.school_id INNER JOIN adoptions ON departments.id=adoptions.department_id";
$fetch = mysqli_query($con, $query) or die(mysqli_error($con));
$row_array = array();
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array[$row['school_name']]['school_name'] = $row['school_name'];
$row_array[$row['school_name']]['terms']['term_name'] = $row['term_name'];
$row_array[$row['school_name']]['terms']['departments'][] = array(
'department_name' => $row['department_name'],
'department_code' => $row['department_code'],
'course_name' => $row['course_name'],
'course_code' => $row['course_code'],
'section_code' => $row['section_code'],
'unique_id' => $row['magento_course_id']
);
}
$return_arr = array();
foreach ($row_array as $key => $record) {
$return_arr[] = $record;
}
file_put_contents("data/iMadeJSON.json" , json_encode($return_arr, JSON_PRETTY_PRINT));
My JSON looks like this:
[
{
"school_name": "School's Name",
"terms": {
"term_name": "FALL 2013",
"departments": [
{
"department_name": "ACCOUNTING",
"department_code": "ACCT",
"course_name": "COST ACCOUNTING",
"course_code": "3315",
"section_code": "10258",
"unique_id": "10311"
},
{
"department_name": "ACCOUNTING",
"department_code": "ACCT",
"course_name": "ACCOUNTING INFORMATION SYSTEMS",
"course_code": "3320",
"section_code": "10277",
"unique_id": "10314"
},
...
The department information is repeated for each course, making the file much larger. I'm looking for a better understanding of how PHP multidimensional arrays in conjunction with JSON works, because I apparently have no idea.
I started from Ian Mustafa reply and I figure out to solve the problem of each loop erasing the previous array.
It's an old thread but I think this could be useful to others so here is my solution, but based on my own data structure (easy to figure out how to adapt it to other structures I think) :
$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"
}
]
}
]
Change your while to this:
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array[$row['school_name']]['school_name'] = $row['school_name'];
$row_array[$row['school_name']]['terms']['term_name'] = $row['term_name'];
$row_array[$row['school_name']]['terms']['department_name'][] = array(
'department_name' => $row['department_name'],
'department_code' => $row['department_code']
);
}
Edit
If you want to achieve result like the example, maybe you should consider using this method:
<?php
$result_array = array();
$fetch_school = mysqli_query($con, "SELECT id, school_name FROM schools") or die(mysqli_error($con));
while ($row_school = mysqli_fetch_assoc($fetch_school)) {
$result_array['school_name'] = $row_school['school_name'];
$fetch_term = mysqli_query($con, "SELECT term_name FROM term_names WHERE school_id = $row_school['id']") or die(mysqli_error($con));
while ($row_term = mysqli_fetch_assoc($fetch_term)) {
$result_array['terms']['term_name'] = $row_term['term_name'];
$fetch_dept = mysqli_query($con, "SELECT id, department_name, department_code FROM departments WHERE school_id = $row_school['id']") or die(mysqli_error($con));
while ($row_dept = mysqli_fetch_assoc($fetch_dept)) {
$result_array['terms']['deptartments']['department_name'] = $row_dept['department_name'];
$result_array['terms']['deptartments']['department_code'] = $row_dept['department_code'];
$fetch_course = mysqli_query($con, "SELECT course_name, course_code FROM adoptions WHERE departement_id = $row_dept['id']") or die(mysqli_error($con));
while ($row_course = mysqli_fetch_assoc($fetch_course)) {
$result_array['terms']['deptartments']['courses']['course_name'] = $row_course['course_name'];
$result_array['terms']['deptartments']['courses']['course_code'] = $row_course['course_code'];
}
}
}
}
file_put_contents("data/iMadeJSON.json" , json_encode($result_array, JSON_PRETTY_PRINT));
Probably it's not an effective program, but it should gives you best result. Hope it helps :)
Try replacing your while loop with below code:
$departments = array();
$courses = array();
$i = 0;
$j = 0;
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array[$row['school_name']]['school_name'] = $row['school_name'];
$row_array[$row['school_name']]['terms']['term_name'] = $row['term_name'];
$key = array_search($row['department_code'], $departments);
if ($key === FALSE) {
$k = $i++;
$departments[] = $row['department_code'];
$row_array[$row['school_name']]['terms']['departments'][$k]['department_name'] = $row['department_name'];
$row_array[$row['school_name']]['terms']['departments'][$k]['department_code'] = $row['department_code'];
} else {
$k = $key;
}
$skey = array_search($row['course_code'], $courses);
if ($skey === FALSE) {
$l = $j++;
$courses[] = $row['course_code'];
$row_array[$row['school_name']]['terms']['departments'][$k]['courses'][$l]['course_name'] = $row['course_name'];
$row_array[$row['school_name']]['terms']['departments'][$k]['courses'][$l]['course_code'] = $row['course_code'];
} else {
$l = $skey;
}
$row_array[$row['school_name']]['terms']['departments'][$k]['courses'][$l]['sections'][] = array('section_code' => $row['section_code'], 'unique_id' => $row['magento_course_id']);
}
Hope this would help you.
I know that this is a kind of an old question, but today I was with the same issue. I didn't find a proper solution online and finally I solved, so I'm posting here so others can check.
I'm not 100% sure that this will work because I don't have your DB, but in my case was similar and worked. Also it will not be 100% like it was asked, but I'm pretty sure there will be no redundancy and all the data will be shown.
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array ['school_name'][$row['school_name']]['terms'][$row['term_name']]['departments']['department_code'][$row['department_code']]['department_name'] = $row['department_name'];
$row_array ['school_name'][$row['school_name']]['terms'][$row['term_name']]['departments']['department_code'][$row['department_code']]['courses']['course_code'][$row['course_code']]['course_name'] = $row['course_name'];
$row_array ['school_name'][$row['school_name']]['terms'][$row['term_name']]['departments']['department_code'][$row['department_code']]['courses']['course_code'][$row['course_code']]['sections']['unique_id'][$row['magento_course_id']]['section_code'] = $row['section_code'];
}
Also I'm not a PHP guy, but from what I understand, the = comes before a leaf and only before a leaf.

PHP code to get the json output in the following format

Hi i have written an android app which interacts with php to get data from the database.
I need the json to return the data back in this format.
[
{
"outlet_id" :"1",
"outlet_desc" :"BigBazaar",
"outlet_loc" :"Jayanagar4thBlock",
"outlet_image" :"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FBigBazaar.png",
"recommended_products": [
{
"item_id":"3",
"item_desc":"Dettol",
"item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FDettol.png"
}
]
},
{
"outlet_id":"2",
"outlet_desc":"FoodWorld",
"outlet_loc":"Basavanagudi",
"outlet_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FFoodWorld.png","
recommended_products":[
{
"item_id":"3",
"item_desc":"Dettol",
"item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FDettol.png"
},
{
"item_id":"3",
"item_desc":"Colgate",
"item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FColgate.png"
}
]
},
{
"outlet_id":"5",
"outlet_desc":"Total",
"outlet_loc":"MurgeshPalaya",
"outlet_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FTotal.png",
"recommended_products":[
{
"item_id":"3",
"item_desc":"Dettol",
"item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FDettol.png"
},
{
"item_id":"3",
"item_desc":"Colgate",
"item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FColgate.png"
}
]
}
]
But right now it is giving in the following format.
[
[
{
"outlet_id": "1",
"outlet_name": "Big Bazaar",
"lat": "12.9285690",
"lng": "77.5831100",
"outlet_image": "images/BigBazaar.png",
"outlet_location": "Jayanagar 4th Block"
}
],
[
{
"outlet_id": "2",
"outlet_name": "Food World",
"lat": "12.9392350",
"lng": "77.5780680",
"outlet_image": "images/FoodWorld.png",
"outlet_location": "Basavanagudi"
}
],
[
{
"outlet_id": "5",
"outlet_name": "Total",
"lat": "12.9589340",
"lng": "77.6571610",
"outlet_image": "images/Total.png",
"outlet_location": "Murugeshpalya"
}
],
[
{
"outlet_id": "6",
"outlet_name": "Big Bazaar",
"lat": "12.9324963",
"lng": "77.6228463",
"outlet_image": "images/BigBazaar.png",
"outlet_location": "Koramangala"
}
],
[
{
"outlet_id": "7",
"outlet_name": "Food World",
"lat": "12.9785055",
"lng": "77.6379353",
"outlet_image": "images/FoodWorld.png",
"outlet_location": "Indira Nagar"
}
]
]
This is my php code.
<?php
error_reporting(0);
//$url = $_GET['url'];
//$mR = $_GET['mRequest'];
//$mOid = $_GET['mOutletId'];
//$mloc = $_GET['mLocation'];
//connect to the db
$user = "root";
$pswd = "";
$db = "recommendations_db";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//if($mR == 'outlets' && $mloc = 'all'){
$query = "SELECT * FROM outlets";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
while($row = mysql_fetch_assoc($result))
{
$output[] = array($row);
}
print( json_encode($output) );
?>
How can i modify the above php code to return in the 1st format. Please help as i am not so good in php.
Table Structure.
Outlets Table.
It contains the following fields.
outlet_id outlet_name lat lng outlet_image outlet_location
Recommendations table.
It contains the following fields.
item_id outlet_id
Items table.
It contains the following fields.
item_id item_name item_image item_price category_id
Ok so it's the missing sub-array. You want to create a JSON string, not a object, from a multidimensional associative array.
There are faster ways to select these rows but this is easy to follow.
$query = "SELECT * FROM outlets";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
$output=array(); # don't leave it undefined
while($row = mysql_fetch_assoc($result))
{
# guessing this query
$query2 = "SELECT * FROM recommended_products WHERE outlet_id=".$result['outlet_id'];
# now we create the sub array recommended_products
$row['recommended_products']=array();
$result2 = mysql_query($query2) or die("Unable to verify user because : " . mysql_error());
while($row2 = mysql_fetch_assoc($result2)){
$row['recommended_products'][]=$row2;
}
# then add the modified row to the output
$output[] = $row;
}
print( json_encode($output) );
Also, mysql_ is depreciated. Probably no genuine need to rush but it's worth at least looking at converting to mysqli or PDO.
Change $output[] = array($row); to $output[] = $row;

Categories