Output data from mysql to array json driving me crazy - php

im trying to pull out a menu in this json format :
check the output : http://www.alacarta.do/iphone/webservices/restaurants_menu2.php?r=415
The thing is that iterating of the Category plates, it duplicates the plates and then add the corresponding correct ones in each Category. all the time. check the output in the link. first category is TO SHARE. and the plates are ok, but the second category FRIES BAR, will throw again the plates from TO SHARE and then the correct plates in its category
<?
$where = empty($_GET['r'])? NULL : 'id = '. intval($_GET['r']);
$restaurant = $cmp->empresas($where,"nombre ASC")->fetch();
$json = array();
$arraynombre = array();
while($orden = $cmp->platos_tipos_orden("id_empresa = {$restaurant->id}","orden ASC")->foreachrow()):
$tipo = $cmp->platos_tipos("id = {$orden->id_tipo}")->fetch();
while($menu = $cmp->platos_menu("id_tipo = {$orden->id_tipo} AND id_empresa = {$orden->id_empresa}")->foreachrow()):
$p = $cmp->platos_lista("id = {$menu->id_plato}")->fetch();
$pnombre = $p->nombre;
$pid = $p->id;
$pprecio = $p->precio;
$arraynombre1 = array('plato_id'=>$pid,'plato_nombre'=>$pnombre,'precio'=>$pprecio);
if (in_array($arraynombre1['plato_id'], $arraynombre['plato_id'])) continue;
$arraynombre[] = $arraynombre1;
endwhile;
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre);
$json[] = $jsondata;
endwhile;
echo json_encode( array("menu"=>$json));
?>

Your issue is probably this line -
$arraynombre[] = $arraynombre1;
as you continually add to the array, not overwrite the previous loops values.
Try adding a key to it that is unique to each loop, ie. $orden->id_tipo -
$arraynombre[$orden->id_tipo][] = $arraynombre1;
Then you would also need to change
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre);
to
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre[$orden->id_tipo]);
note- it is hard to follow all your code logic, so [$orden->id_tipo] might need to be [$orden->id_empresa] or could be a similar counter var [$x] that you increase on each loop.

Related

Update One JSON Field in Database - CodeIgniter

I have a JSON field called 'spec' and there are about 10 other items in this in JSON format. I need to only update the quantity.
Although when I try this method, it deletes everything else in it and just sets spec = quantity.
Heres what I have so far.
$pass_coupon_id = $this->pass_coupon_id();
$coupon_array = $this->db->query("SELECT * FROM coupon WHERE coupon_id='$pass_coupon_id'")->result_array();
foreach ($coupon_array as $row) {
$spec = json_decode($row['spec'], true);
}
$quantity_new = $spec['quantity'] - 1;
$data2 = array(
'spec' => json_encode(array(
'quantity'=> $quantity_new
)));
$this->db->where('coupon_id', $pass_coupon_id);
$this->db->update('coupon', $data2);
You need to overrite only this one field and update whole field in query.
<?php
$pass_coupon_id = $this->pass_coupon_id();
$coupon_array = $this->db->query("SELECT * FROM coupon WHERE coupon_id='$pass_coupon_id'")->result_array();
// i don't know what you're using, but using foreach to extract single row isn't good solution. Look for sth like result_row() maybe.
$coupon = $coupon_array[0];
$spec = json_decode($coupon, true);
$new_quantity = $spec['quantity'] - 1;
$spec['quantity'] = $new_quantity;
$new_spec = json_encode($spec);
$this->db->where('coupon_id', $pass_coupon_id);
$this->db->update('coupon', $new_spec);
Depending on the database, the best solution would be using specific function to ommit updating whole structure - https://stackoverflow.com/a/34987329/2926214

Filling a two dimensional array with mysql fetch results in php

I just had a framework for creating charts and this is how it works normally.
$p = new chartphp();
$p->data = array(array(
array("A",2),
array("B",3),
array("C",23),
array("D",10)
));
$p->chart_type = "bar";
// Common Options
$p->xlabel = "My X Axis";
$p->ylabel = "My Y Axis";
$out = $p->render('c1');
This way it works perfectly fine, now I need to get results from a sql query and fill the array.
$query ="SELECT t.date AS dates,COUNT(t.id) AS trans FROM Gab AS g, Transaction AS t WHERE t.date BETWEEN '2015-07-30' AND '201-07-10' AND g.TID = '1401009' ORDER BY DATES";
$ask = mysql_query($query) or die("Error");
//Now I try to load the results into the array to be integrated into the API.
$p = new chartphp();
$p->data = array(array(
while($recon = mysql_fetch_array($ask)
{
array($recon['dates'],recon['trans']),
}
));
$p->chart_type = "bar";
// Common Options
$p->xlabel = "My X Axis";
$p->ylabel = "My Y Axis";
$out = $p->render('c1');
I tried this but it does not work, the array dont seem to be loaded !
I'm actually not sure what nesting a while like you have would do and I'm unable to experiment at the moment, but something like this should get you in the right direction:
$p->data = array(array());
while($recon = mysql_fetch_array($ask))
{
$p->data[0][] = array($recon['dates'], $recon['trans']);
}
Initializing the array and then appending the elements in the loop.

PHP / Zend / Google Spreadsheet not getting all rows

I am trying to get all the rows from a Google spreadsheet via a PHP/Zend script. This is the script I am using:
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient('xxxxxxxxx', 'xxxxxxx', $service);
$spreadsheetService = new Zend_Gdata_Spreadsheets($client);
// Get spreadsheet key
$spreadsheetsKey = 'xxxxxxxxxxxxx';
$worksheetId = 'xxx';
// Get cell feed
$query = new Zend_Gdata_Spreadsheets_CellQuery();
$query->setSpreadsheetKey($spreadsheetsKey);
$query->setWorksheetId($worksheetId);
$cellFeed = $spreadsheetService->getCellFeed($query);
// Build an array of entries:
$ssRows = array();
$ssRow = array();
$titleRow = array();
$tableRow = 1;
foreach($cellFeed as $cellEntry) {
$row = $cellEntry->cell->getRow();
$col = $cellEntry->cell->getColumn();
$val = $cellEntry->cell->getText();
// Add each row as a new array:
if ($row != $tableRow) {
array_push($ssRows, $ssRow);
$ssRow = array();
// Move to the next row / new array
$tableRow = $row;
}
// Build the array of titles:
if ($row == 1) {
$titleRow[$col] = $val;
}
// Build the array of results with the title as the key:
else {
$key = $titleRow[$col];
$ssRow[$key] = $val;
}
}
// Pass the results array:
return array_reverse($ssRows);
This builds me an array with MOST of the details from the spreadsheet, however it always misses off the last entry - can anyone see what I am doing wrong, or is there a better way to get all the data from the spreadsheet?
The form is a 3 part form, based on different answers. On filling out one part, I want to display a URL back to the form, with some details from the first form pre-filled to make the second part of the form faster to fill out. This is all fine, it is simply the missing last entry that is the major problem!
Thanks!
Your code works like this:
if (next_row) {
data[] = current_row
current_row = array();
}
if (first_row) {
title_row logic
} else {
add cell to current_row
}
So you only add the rows to your collector once you go to the next row. This will miss the last row because you'll miss that last transition.
The easy fix is to add array_push($ssRows, $ssRow); right after the foreach loop. You will need to add a check for 0 rows, this should be skipped then.
Perhaps a more proper fix is to iterate by row, then by cell, rather than just by cell.

Trouble creating array

I have a problem…
I am trying to create an array from a mysql table.
But I don’t know how to format the data coming out of MySQL into an array in php.
Here is what I have done so far...
//Generate Org Data
$result_org = mysql_query("SELECT emp_no,sup_empno,Name,Title FROM employees");
// Initializes a container array
$orgArray = array();
while($row = mysql_fetch_array($result_org, MYSQL_ASSOC))
{
$currempno = $row['emp_no'];
$currsupervisor = $row['sup_empno'];
$currtitle = $row['Name']. '\n ' .$row['Title'];
// This is where I haven't a clue to get it the right format...??
// Stores each database record to an array
$buildorg = array("$currempno","$currsupervisor","$currtitle");
// Adds each array into the container array
array_push($orgArray, $buildorg);
}
// show the data to verify
echo ($orgArray);
// the data needs to be exactly like this below
o.addNode(003, 002, '', 'Jane Doe\nAsst Manager');
where 003 is the $currempno 002 is the $currsupervisor Jane Doe\nAsst
Manager is $currtitle
getting the o.addNode( along with the commas and double quotes and ending );
around this has me perplexed
Any help would be appreciated…
K Driscoll
If I understand correctly, you are actually trying to create line
o.addNode(003, 002, '', 'Jane Doe\nAsst Manager');
so just put the values into the string and format it the way you want to - there is no need to create another array - you can create final strings and push those into the array:
$currempno = $row['emp_no'];
$currsupervisor = $row['sup_empno'];
$currtitle = $row['Name']. '\n ' .$row['Title'];
$output = sprintf("o.addNode(%03d, %03d, '', '%s');", $currempno, $currsupervisor, $currtitle);
array_push($orgArray, $output);
I guess this is what you are look for, more or less:
$finalArray = array();
$result_org = mysql_query("SELECT emp_no,sup_empno,Name,Title FROM employees");
while( $row = mysql_fetch_array($result_org, MYSQL_ASSOC) ) {
$finalArray[] = array(
$row['emp_no'],
$row['sup_empno'],
$row['Name'].'\n'.$row['Title']
);
}
print_r($finalArray);
You used array_push function, better use another construction: $someArray[] = $newElement; — it has to do same. Example below.
This code will work:
//Generate Org Data
$result_org = mysql_query("SELECT emp_no,sup_empno,Name,Title FROM employees");
// Initializes a container array
$orgArray = array();
while($row = mysql_fetch_array($result_org, MYSQL_ASSOC))
{
$currempno = $row['emp_no'];
$currsupervisor = $row['sup_empno'];
$currtitle = $row['Name']. '\n ' .$row['Title'];
$orgArray[] = array($currempno, $currsupervisor, $currtitle);
}
var_dump($orgArray);

PHP json_encoding datas with parent and child categories

Iam trying with the json_encoding for about two hours but iam not getting the output as required. Actually this is a requirement for the mobile application developer who is asking in the format which i will explain here.The code below is what i have tried:
include_once("class_connection.php");
//Getting the Parent Category
$sqlStr = mysql_query("select catname , id from `category` where `parentid`='0'");
$jsonArray = array();
while ($fetchStr = mysql_fetch_assoc($sqlStr)) {
$jsonArray[] = array("ParentCategory" => $fetchStr["catname"]);
$id = $fetchStr['id'];
//Getting child categories from the above parent
$sqlChildStr = mysql_query("SELECT catname,id,parentid FROM `category` where `parentid`='$id'");
while ($fetchchildStr = mysql_fetch_assoc($sqlChildStr)) {
$jsonArray[] = array("ChildCategory" => $fetchchildStr["catname"]);
}
}
echo json_encode(array("JsonOutput" => $jsonArray)) . "<br />";
The Output is :
"JsonOutput":[{"ParentCategory":"Animals"},{"ChildCategory":"Bear"},{"ChildCategory":"Deer"},{"ChildCategory":"Dolphins"},
{"ParentCategory":"Art"},{"ChildCategory":"Hand Painting"},{"ChildCategory":"Painting"},{"ChildCategory":"3D"},{"ChildCategory":"Abstract"}]}
Here , in the above output the parent category array is empty without its child category array. I want to store all the child category array in its parent category array and finally i have to store both parent and child category into the JsonOutput array so i want the output as
"JsonOutput":[{
"ParentCategory":"Animals" : [{
{"ChildCategory":"Bear"},{"ChildCategory":"Deer"},{"ChildCategory":"Dolphins"}
]}
"ParentCategory":"Arts" : [{
{"ChildCategory":"Hand Painting"},{"ChildCategory":"Painting"},{"ChildCategory":"3D"}, {"ChildCategory":"Abstract"}
]}
]}
You probably need to do this (only the important bits are shown):
$jsonArray = array();
while ($parentCat = mysql_fetch_assoc($sqlStr)) {
$temp = array(
"ParentCategory" => $parentCat["catname"]
);
while ($childCat = mysql_fetch_assoc($sqlChildStr)) {
$temp["ChildCategory"][] = array(
"ChildCategory" => $childCat["catname"]
);
}
$jsonArray[] = $temp;
}
I used a temporary variable for storing and manipulating the parent category. This gets added to the main array at the end of loop.
Please use the following codes, give the index inside the while loop...
$jsonArray = {};
while ($fetchStr = mysql_fetch_assoc($sqlStr)) {
//$jsonArray[] = array("ParentCategory" => $fetchStr["catname"]);
$id = $fetchStr['id'];
//Getting child categories from the above parent
$sqlChildStr = mysql_query("SELECT catname,id,parentid FROM `category` where `parentid`='$id'");
while ($fetchchildStr = mysql_fetch_assoc($sqlChildStr)) {
$jsonArray["ParentCategory"][$fetchStr["catname"]] = array("ChildCategory" => $fetchchildStr["catname"]);
}
}
echo json_encode(array("JsonOutput" => $jsonArray)) . "<br />";

Categories