Get rid of the int index in json_encode in PHP for multidimensional arrays

This is a bit of a difficult problem to explain, so do not show you well. 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 an application using it, it cannot handle "0" :, "1", instead, it just wants to be separated by commas.

My current code to generate:

while ($r = mysql_fetch_assoc($q)) {
        $array[] = $r;
    }
json_encode($array);

Pretty simple and raw stuff at the moment. But I think that I may have to write json_encode for myself so that it prints it like this .....

Any help would be greatly appreciated.

NOTE. This is a valid form (hand written):

{
"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"
}
+3
source share
3 answers

, (0, 1) , (total, ajax_message ..). :

$a = array();
while ($r = mysql_fetch_assoc($q)){
    $a[] = $r;
}
$a['key'] = value;

:

$a = array();
$a['rows'] = array();
while ($r = mysql_fetch_assoc($q)){
    $a['rows'][] = $r;
}
$a['key'] = value;

($a['rows'] ) , json_encode() [{list}, {like}, {this}]

+3

.

:

array( 
  'data' => array(
    '0' => array()
    '1' => array()
    'total' => 2,
    'etc' => 'blah'
  )
)

:

array( 
  'data' => array(
    array(),
    array()
  )
  'total' => 2,
  'etc' => 'blah'
)

, , () , , . PHP, JSON, .

json_encode JSON, , JSON.

+1
while ($r = mysql_fetch_assoc($q)) {
    $array[][] = $r;
}
json_encode($array);
0
source

All Articles