Get rid of the int index in json_encode in PHP for multi-dimensional arrays
extjs, json, php, touch
Solution
The problem is that your numeric keys (`0`, `1`) are at the same level in the hash as named keys (`total`, `ajax_message`, etc). Instead of doing this:
$a = array();
while ($r = mysql_fetch_assoc($q)){
$a[] = $r;
}
$a['key'] = value;
Do this:
$a = array();
$a['rows'] = array();
while ($r = mysql_fetch_assoc($q)){
$a['rows'][] = $r;
}
$a['key'] = value;
If every key in the array (`$a['rows']` in this example) is numeric, `json_encode()` will output it as a `[{list}, {like}, {this}]`
Problem
This is a little bit of a hard problem to explain, so ill show you instead. If you look below you will see valid JSON. ``` { "data":{ "0":{ "action_id":"1", "date":"2012-04-10 15:07:38", "action_type":"1", "action_text":"Some one got blamed!" }, "1":{ "action_id":"2", "date":"2012-04-10 16:18:05", "action_type":"1", "action_text":"Testing multiple items for AJAX" }, "total":2, "ajax_message":"Success", "ajax_status":"0", "success":"true" } } ``` But for the application were using it cannot handle the "0": ,"1", it instead just wants it comma separated . My current code to generate this is: ``` while ($r = mysql_fetch_assoc($q)) { $array[] = $r; } json_encode($array); ``` Fairly simple and raw stuff at the moment. But i think i may have to write a json_encode for myself in order for it to print it like this..... Any help would be greatly appreciated NOTE: This is a valid form(written by hand): ``` { "data": [ { "action_id": "1", "date": "2012-04-10 15:07:38", "action_type": "1", "action_text": "Some one got blamed!", "fb_id": "760775384" }, { "action_id": "2", "date": "2012-04-10 16:18:05", "action_type": "1", "action_text": "Testing multiple items for AJAX", "fb_id": "760775384" } ], "total": 2, "ajax_message": "Success", "ajax_status": "0", "success": "true" } ```