0

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.

12
  • 2
    Do you see? ,"queryType":"profile"}{"success":"true", Two touching {}{}! Aren't you accidentally print the result json twice? I edited your json, added a newline between the two objects. Commented Jun 29, 2012 at 22:10
  • Yes I do, but how do I go about fixing this? Again this is one of my first attempts working with multi-dimensional JSON arrays. Commented Jun 29, 2012 at 22:12
  • 1
    Is your echo $encodedJSON; wrapped into another loop that you didn't copied here? json_encode won't generate such an output. Commented Jun 29, 2012 at 22:14
  • 1
    Your problem is that this code is running in a larger loop that you haven't shown. Rather than $encodedJSON = json_encode($result); echo $encodedJSON; there, you should simply do $outerArray[] = $result; and convert $outerArray to JSON after the loop and echo that. Obviously you should declare $outerArray = array() before the loop as well ;-) Commented Jun 29, 2012 at 22:15
  • 1
    D'you know what, quick fix because I really don't have the energy ATM, change it to this Commented Jun 29, 2012 at 22:35

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Based on the error message, the JS that is throwing the error is JSON.parse(str);
0

Your code should look like this:

global $result;
$result = array();
.......    

if ($action == 'profile') {
  while{{{{{{{{...}}}}}}}}}}}

  $encodedJSON = json_encode( $result );
  echo $encodedJSON;
}

6 Comments

Only problem is that this will only output $result from that last iteration. I would guess the desired result would be a collection of all the $results in an array
Yes, he should consider ernie's answer too, that array_merge thing smells badly.
That whole code makes me recoil in horror frankly - nested iteration of 3 result sets, and as I commented before, 8 sets of braces closing in one place, and probably a gaping SQL inject hole as well (I'm guessing). But we were all young once... ;-)
Maybe you should write $result[] = array_merge($nameArray, $nameResult[$i]); This syntax: $array[]='a new element' appends a new element to the array.
@jtorraca see my answer below - you're only get the last result due to the way you keep re-assigning $result. I'm also assuming you want your JSON output to look like what you had in this question: stackoverflow.com/questions/11257490/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.