I'm creating an API for my website. That API will be used by other developers or an Android application. Well, I have two kind of data structures:
One:
$iterator = 0;
while (($end = $sth->fetch()) && $iterator < 2)
{
$api_arr["data"][] = array(
"id" => $end["id"],
"title" => $end["title"],
"content" => $end["content"] );
$iterator ++;
}
/* Output: ------------ print_r($api_arr); -------------------
Array
(
[data] => Array
(
[0] =>
(
[id] => value_id_1
[title] => value_title_1
[content] => value_content_1
)
[1] =>
(
[id] => value_id_2
[title] => value_title_2
[content] => value_content_2
)
)
) */
/* Output: ------------ echo json_encode($data); -------------------
----- and using JSONveiw extension on chrome -----
{
- data: {
- 0: {
id: "value_id_1",
title: "value_title_1",
content: "value_content_1"
},
- 1: {
id: "value_id_2",
title: "value_title_2",
content: "value_content_2"
},
}
} */
Two:
$iterator = 0;
while (($end = $sth->fetch()) && $iterator < 2)
{
$api_arr["data"]['id'][] = $end["id"];
$api_arr["data"]['title'][] = $end["title"];
$api_arr["data"]['content'][] = $end["content"];
$iterator ++;
}
/* Output: ------------ print_r($api_arr); -------------------
Array
(
[data] =>
(
[id] => Array
(
[0] => value_id_1
[1] => value_id_2
[2] => value_id_3
),
[title] => Array
(
[0] => value_title_1
[1] => value_title_2
[2] => value_title_3
),
[content] => Array
(
[0] => value_content_1
[1] => value_content_2
[2] => value_content_3
)
)
) */
/* Output: ------------ echo json_encode($data); -------------------
----- and using JSONveiw extension on chrome -----
{
- data: {
- id:[
"value_id_1",
"value_id_2",
"value_id_3
],
- title:[
"value_title_1,
"value_title_2,
"value_title_3,
],
- content:[
"value_content_1",
"value_content_2",
"value_content_3
],
}
} */
So, Which data-structure is better for using it in client side? (other websites, mobile-app)
In the first one you are simulating the use of an array without actually using an array (or at least it looks like given your output), and in the second one you are repeating info and forcing the developer to put it all together. The best solution is:
{
data: [
{
id: "",
title: "",
content: ""
},
{
id: "",
title: "",
content: ""
}
]
}
I think this is pretty similar to your first option, but looks like the plugin is showing it in a bad way or something.
The main reason why Android devs prefer that is because a direct translation between objects and json can be done with some libraries.