PHP JSON Array Formatting - php

Let me first start off, sorry for the confusing title. I didn't know how to exactly describe it but here goes. So I am querying a database for string. If there is only 1 result found then it is relatively easy to create an array, fill it with information, encode JSON and return that. I am confused as to when there are multiple results. The code below is what I am using but I highly doubt it is correct. I can't encode it into JSON format using my method which is what I need. If you can help at least point me in the correct direction, I would be more than grateful! Thank you!
PHP:
if ($action == 'profile') {
while ($pson = mysql_fetch_array($personQuery)) {
$typeSearch = 'profile';
$profQuery = mysql_query("SELECT * FROM tableName WHERE ColumnName LIKE '$query'");
$compQuery = mysql_query("SELECT * FROM tableName2 WHERE ColumnName LIKE '$query'");
if ($profQuery && mysql_num_rows($profQuery) > 0) {
$personQueryRows = mysql_num_rows($profQuery);
while ($row = mysql_fetch_array($profQuery)) {
if ($compQuery && mysql_num_rows($compQuery) > 0) {
while ($com = mysql_fetch_array($compQuery)) {
if (mysql_num_rows($profQuery) > 1) {
$compQueryRows = mysql_num_rows($compQuery);
if ($compQueryRows > 0) {
$compReturn = "true";
} else {
$compReturn = "false";
}
$nameArray = Array(
"success"=>"true",
"date"=>date(),
"time"=>$time,
"action"=>$action,
"returned"=>"true"
);
global $result;
for ($i=1;$i<=$personQueryRows;$i++) {
$nameResult[$i]=Array(
"id"=>$row['id'],
"name"=>$row['name'],
"gender"=>$row['gender'],
"comp"=>$row['company'],
"queryType"=>"profile"
);
$result = array_merge($nameArray, $nameResult[$i]);
}
$encodedJSON = json_encode($result);
echo $encodedJSON;
}
}
}
}
}
}
}
}
Returned JSON:
{"success":"true","date":"Jun 29 2012","time":"14:43:16","action":"profile","returned":"true","id":"14321","name":"John Smith","gender":"male","comp":"ABC Studios, LLC.","queryType":"profile"}
{"success":"true","date":"Jun 29 2012","time":"14:43:16","action":"profile","returned":"true","id":"292742","name":"John Smith","gender":"male","comp":"DEF Studios, LLC.","queryType":"profile"}
JavaScript error (when parsing JSON):
Uncaught SyntaxError: Unexpected token {
P.S. I am just getting started with PHP Arrays, and JSON formatting so I apologize if this is totally wrong. Still in the learning phase.

It looks like you're building up $nameResult[$i], but then you do:
$result = array_merge($nameArray, $nameResult[$i]);
You're doing that in each iteration of that for loop (once for each of the rows you got back), meaning that each time, you're clobbering $result.
After you finish that for loop, you then take whatever $result finally is (meaning the last $personQueryRows), and then json_encode it.
Looking at your other question (http://stackoverflow.com/questions/11257490/jquery-parse-multidimensional-array), it looks like what you should really be doing is before the loop where you go over $personQueryRows:
$output=$nameArray;
And then replace the array_merge line with:
$output[] = $nameResult[$i];
That last line will append the $result array onto the $output array as a new array member, meaning that it's nesting the array, which is what you'll need for your nested JSON.

Your code should look like this:
global $result;
$result = array();
.......
if ($action == 'profile') {
while{{{{{{{{...}}}}}}}}}}}
$encodedJSON = json_encode( $result );
echo $encodedJSON;
}

Related

PHP json_encode & SQL server callback function returns only one result

I'm trying to set up a PHP callback function for use in our application. It needs to pull data from a SQL server, and while I can get it to work initially, it's not quite doing what I want.
Code:
//Callback function for passing queries
function queryCallback($conn, $query) {
$response = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($response)){
if ($row === false) {
die(print_r(sqlsrv_errors(), true));
}
$responseData[] = $row;
}
foreach($responseData as $v) {
$output[key($v)] = current($v);
}
$responseDataJSON = JSON_encode($output, 128);
return $responseDataJSON;
}
In the above, $conn represents our server creds, as passed to sqlsrv_connect(), and $query is the string containing the query passed to SQL. Both have been verified as working.
Issue:
This code contacts the server correctly, and runs the query, but it only returns one result. This is obviously a problem with how the loops are set up, but I just can't spot it
My feeling is that the following $row = sqlsrv_fetch_array($response) is fetching the whole row as an array, but your usage of $output[key($v)] = current($v) is only returning the first column with the same key, and overwriting the $output index with every iteration.
foreach($responseData as $v) {
$output[key($v)] = current($v);
}
lets say you instead perform
foreach($responseData as $k => $v) {
$output[$k] = $v;
}
At which point this is redundant as $responseData[] already is this structure.
You may actually want this if you plan to extract just the first column out of your row.
foreach($responseData as $v) {
$output[] = current($v);
}

Using array from header in another page

Ok so I have an array "$landing" in my header.php, then in my page.php I include the header.php but for some reason when I call the 'Name' field in the array in the page.php: echo $landing['Name']; it just doesn't work.
this is how the array is being filled up, and calling it in the header works perfectly.
$landing = array();
while ($row = mysql_fetch_array($result)) {
$str = strtolower($row['Name']);
if ($str == $name) {
$landing = $row;
}
}
To clarify, $row and $landing are both arrays, and both have multiple fields 'Name' 'Color' 'Info'.
What am I doing wrong here? Do I need to make it global somehow or what's going on?
The original code works somehow, now as the OP said in a comment.
But my old tips still hold:
Consider using MySQLi or PDO instead of the deprecated MySQL extension!
Why do you compare the dataset's column value on the client-side? You can do this on the MySQL side, it'll be faster!
You are, as ComFreek correctly stated, turning $landing into a string. Instead, if you're trying to add an entry to the landing array, use [] brackets which mean "add into new entry".
$landing = array();
while ($row = mysqli_fetch_array($result)) {
$str = strtolower($row['Name']);
if ($str == $name) {
$landing[] = $row;
}
}
I cant comment LS97 post, anyway you want to use $landing["Name"] you edit LS97 code into this:
$landing = array();
while ($row = mysqli_fetch_array($result)) {
$str = strtolower($row['Name']);
if ($str == $name) {
$landing["name"] = $row;
}
}
If you want to use multiple names, LS97 code is fine.
The problem is what they said. (Using $landing = $row, landing will be a string.)

Recursively add to an array

I'm struggling to understand a problem that i've got with recursion where by I am traversing down a hiearchy in only one direction and adding all the children of each parent to an array.
However I can't quite work out the best way to continuously add to that array while using recursion.
Here is what my function looks like so far. I'd appreciate it hugely if someone could push me in the right direction with this.
function getTaxChildrenList($cat, $data){
$next = get_terms('location_types', 'orderby=count&hide_empty=0&parent='.$cat);
if(count($next)){
$result = array();
foreach($next as $next_key => $next_level){
$result[$next_level->term_id] = $this->getTaxChildrenList($next_level->term_id, $result);
}
}
return $result;
}
I now have the structure being returned as I want but need to actually add the objects of each of these children to the key which i'm guessing might be my base case.
Screenshot -> http://cl.ly/image/1z1v2S243f3H
So perhaps you need something like this:
function getTaxChildrenList($cat){
$next = get_terms('location_types', 'orderby=count&hide_empty=0&parent='.$cat);
$result = array();
if(count($next)){
foreach($next as $next_key => $next_level){
$result[$next_level->term_id] =
array("data" => $next_level->something,
"children" => $this->getTaxChildrenList($next_level->term_id));
}
}
return $result;
}
Is it something like that?
This should do the job
function getTaxChildrenList($cat) { //no second parameter
$next = get_terms('location_types', 'orderby=count&hide_empty=0&parent='.$cat);
$result = array();
//base case would be count($next) == 0
if(count($next)){
foreach($next as $next_level){
//add recursively arrays
$recur = $this->getTaxChildrenList($next_level->term_id);
if(count($recur) == 0)
$result[$next_level->term_id] = $next_level;
else
$result[$next_level->term_id] = $recur;
}
}
return $result;
}

If true use foreach loop, else use while

I'm trying to link the MySQL while loop into foreach loop using something like this :
if($something == true){
foreach($array as $arr){
} else {
while($row = mysql_fetch_array($mysql_query)){
}
// loop instructions
}
It looks so wrong, I know but you see what I am trying to do ?.. I want to grab data from array if $something was true, else then grab data from database
I had another solution idea and its to manually match the array with how $mysql_query works so I can use them both with while only, something like this :
if($something == true){
$mysql_query = array("username" => "$_GET['username']", "password" => "$_GET['password']");
} else {
$mysql_query = mysql_query("SELECT * FROM users WHERE usern......");
}
while($row = mysql_fetch_array($mysql_query)){
...
That's a second way to do it but it looks wrong as well because the first array is normal, I want to match that normal array with how mysql_query builds it so it can fit with the while loop
P.S. : I DO NOT want to repeat writing the loop instructions, I want them both to work with only one like I mentioned above
Put your processing into a function:
function process_data($data) {
// do stuff
}
if($something){
foreach($array as $arr){
process_data($arr);
}
} else {
while($row = mysql_fetch_array($mysql_query)){
process_data($row);
}
}
The other answers here are fine, but you'd be better served just to make sure that $array is a valid array regardless of something ... How about
if (!something){
$array = array();
while($row=mysql_fetch_array($mysql_query)) {$array[] = $row;}
}
foreach($array as $arr){
// do work
}
You'd probably get a better answer if you expanded the scope of what you've explained a bit. Without knowing what the something is and what the data is, plus the ultimate objective then it's hard to tell what kind of structure you should be using.
It seems to me that you could achieve this by just using a function, if the code inside the loop is the same. Like this:
if($something == true)
{
foreach($array as $arr)
{
doWork($arr);
}
}
else
{
while($row = mysql_fetch_array($mysql_query))
{
doWork($row);
}
}
function doWork($arr)
{
//...
}
You cannot nest loop instructions inside a loop like this. You'll need to have two separate loops completely inside the IF statements.
if($something == true){
foreach($array as $arr){
// do work
}
} else {
while($row = mysql_fetch_array($mysql_query)){
// do work
}
}
Maybe you could look at from this viewpoint. And take note that this code uses mysql_fetch_assoc() instead of mysql_fetch_array(). Try both functions and look at the resulting rows with var_dump(). You will see that mysql_fetch_array() has twice as much data. You may want that, but probably not.
if ($something !== true)
{
$array = array();
while($row = mysql_fetch_assoc($mysql_query_result_resource))
{
$array[] = $row;
}
}
foreach($array as $arr)
{
/* PROCESS */
}

function php with while loop

Hello i am trying to make function with while loop in php but cant getting write here is my code
function mail_detail($mail_detail){
$data= mysql_query("select * from messages where messages.to = '$mail_detail' and to_viewed = 0 ORDER BY messages.id DESC");
while ($result= mysql_fetch_array($data)){
return $result;
}
}
and out put is
$mail_detail= mail_detail($userid)
echo '<li class="read">
<a href="#">
<span class="message">'. $mail_detail['title'].'</span>
<span class="time">
January 21, 2012
</span>
</a>
</li>';
i am not getting all values just getting one value please help
thx
The return statement is terminating your loop and exiting the function.
To get all values, add them to an array in the loop, and then return the array. Like this:
$results = array();
while ($result = mysql_fetch_array($data)) {
$results[] = $result;
}
return $results;
on the side that receives the array
$msgArray = mail_detail($mail_detail);
foreach($msgArray as $msg) {
//use $msg
}
To add on, a function is only able to return once (except for some special circumstances that you should not worry about). Therefore, the first time your function comes across a return statement, it returns the value and exits.
This functionality of return can often be used to your advantage. For example:
function doSomething($code = NULL)
{
if ($code === NULL) {
return false;
}
//any code below this comment will only be reached if $code is not null
// if it is null, the above returns statement will prevent control from reaching
// this point
writeToDb($code);
}
function mail_detail($mail_detail){
$returnArr = array();
$data= mysql_query("select * from messages where messages.to = '$mail_detail' and to_viewed = 0 ORDER BY messages.id DESC");
while ($result= mysql_fetch_array($data)){
$returnArr[] = $result;
}
return $returnArr;
}
This way you return everything returned because you push it in one array and as your loop finishes, the whole array wil be returned. Because just like xbones said, a return breaks your loop!
harinder,Function(mysql_fetch_array($data)) return an array. That means your $result is an array, so when you recevie the $result at view page you have to extract it using foreach look
like this:
foreach($result as $item)
{
echo $item->user(<-here you have to write the column name ,that you want to retrieve)
}
Hence you can get your all results in array.

Categories