3

I want to create a JSON object from my MySQL results with PHP so I can pass it to JavaScript. I don't quite understand the difference between JSON array and JSON object.

This is how I do it. But is there a better way? This is the array way I believe?

$json = array();
while($r=mysql_fetch_array($res)){
  $json['firstname'] = $r['firstname'];
  $json['lastname'] = $r['lastname'];
}
echo json_encode($json);

I want to be able to get the info from JavaScript, by selecting all first names only If I wish etc..

0

2 Answers 2

11

you can try this, fetch data and push to array, then echo that array

$info=array();
while($row = mysql_fetch_array($res,MYSQL_ASSOC)){
array_push($info,$row);
}
echo json_encode($info);

would return

array(2) { [0]=> array(3) { ["id"]=> string(1) "1" ["firstname"]=> string(3) "foo" ["lastname"]=> string(3) "bar" } [1]=> array(3) { ["id"]=> string(1) "2" ["firstname"]=> string(3) "foo" ["lastname"]=> string(3) "bar" } }

json

[{"id":"1","firstname":"foo","lastname":"bar"},{"id":"2","firstname":"foo","lastname":"bar"}]
Sign up to request clarification or add additional context in comments.

Comments

2

Well this would encode every row, with each row being the JSON Object:

$json = array();
while($r=mysql_fetch_array($res)){
  $json[] = $r;
}
echo json_encode($json);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.