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:
which would result in the json: