JSON编码的最佳格式?

I'm not familiar with PHP and JSON but need it for my Android project.

I'm confused about which JSON format is the most effective. Most examples I saw use Associative array by using this code:

$result = mysql_query($queryString)
while($row = mysql_fetch_assoc($result)){
    $json['contact']['ID'] = $row['ID'];
    $json['contact']['Name'] = $row['Name'];
}

Format #1

{"contact":{"ID":"1","Name":"Andy"}}

I like that format but I don't know how to make each key hold more than one value. So when my query returns Andy and Bob, the json will only contains Bob.

Then, I found this PHP code:

while($row = mysql_fetch_row($result)){
    $json['contact'][] = $row;
}
echo json_encode($json);

It makes the json looks like this:

Format #2

{"contact":[["1","Andy"],["2","Bob"]]}

But in Android, there is no JSONObject method to getArray(). Even if there is, I want to avoid using numbered array that requires [0] or [1] to be called.

So, which one is better? Or any other alternative?

Thanks

It's not that one method is more "effective" than the other, they serve different purposes. One is an associative object, and the other is a indexed array.

In your case, it looks like you want a list (indexed array) of objects. So what i would recommend doing is:

$result = mysql_query($queryString)
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
    $json['contact'][] = $row;
}
echo json_encode($json);

which would result in the json:

{"contact":[{"ID":"1","Name":"Andy"}, {"ID":"2","Name":"Bob"}]}

Why not use mysql_fetch_array(); ?

{"contacts":[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]}

An object with key contacts that contain an array of contact objects perhaps?

You can also do it hardcoded (not as nice as mysql_fetch_array() tho.);

$result = array();
$i = 0;
while(...) {
  $result[] .= '{"id":"'.$i.'","name":"'.$fetch['name'].'"}';
  $i++;
}
echo "[".implode(',', $result)."]";