PHP - 获取json数据

I have problem with this script...

My script has return this:

{
"categories": {
    "cid": "1",
    "name": "Pierwsza pomoc"
}
}{
"categories": {
    "cid": "2",
    "name": "Poradniki"
}
}{
"categories": {
    "cid": "3",
    "name": "Klany"
}
}{
"categories": {
    "cid": "4",
    "name": "Eventy, imprezy"
}
}{
"categories": {
    "cid": "5",
    "name": "Rozm\u00f3wki"
}
}{
"categories": {
    "cid": "6",
    "name": "Quest, solucje"
}
}{
"categories": {
    "cid": "7",
    "name": "Off topic"
}
}

But i want to this

[
    'categories': {
          'cid': 1,
          'name': 'test',
          'cid': 2,
          'name': 'asdsad',
          'cid': 3,
          'name': 'asdasd'
    }
]

Code used to create the data is

if($query->rowCount() > 0){ 
    foreach($query as $row){ 
        $Forum->writeJSON(array('categories' => array( 'cid' => $row['id'], 'name' => $row['name'] ))); 
    } 
}



class Forum { 
    public function writeJSON($array){ 
        echo json_encode($array, JSON_PRETTY_PRINT); 
    } 
} 

$Forum = new Forum;

Well, this structure is not possible. You cannot store two or more elements with exactly same key in same object. However maybe you simply want this output:

[ 'categories' : { 1: {category_id:1, name:'test'}, 2: {category_id:2, name:'test'} } ]

It is simple, for example, you can use something like this to form that array:

<?php
//fetch data into categories variable
$output = array();
$output['categories'] = array();
foreach ($category as $category){
  $output['categories'][] = array('category_id' => $category['id'], 'name' => $category['name']);
}
$output = json_encode($output);
?>

PS: Please use the correct variable names in your code, this is just an example using fictitious variable names

You need to change your foreach loop code

if($query->rowCount() > 0){ 
 foreach($query as $row){
    $cat_array[$row['id']] = array('cid'=>$row['id'],'name'=>$row['name']);
 }
  $json_array[] = array('categories'=>$cat_array);
  $Forum->writeJSON($json_array);
}