2012-09-15 102 views
1

數據庫查詢返回幾個行,我遍歷如下:需要幫助建立JSON數組

foreach ($query->result() as $row) { 

     $data[$row->post_id]['post_id']   = $row->post_id; 
     $data[$row->post_id]['post_type']  = $row->post_type; 
     $data[$row->post_id]['post_text']  = $row->post_text; 
    } 

如果我json_encode所得陣列($a['stream'])我得到

{ 
    "stream": { 
     "1029": { 
      "post_id": "1029", 
      "post_type": "1", 
      "post_text": "bla1", 
     }, 
     "1029": { 
      "post_id": "1030", 
      "post_type": "3", 
      "post_text": "bla2", 
     }, 
     "1029": { 
      "post_id": "1031", 
      "post_type": "2", 
      "post_text": "bla3",    
     } 
    } 
} 

json應該看起來像這樣:

{ 
    "stream": { 
     "posts": [{ 
      "post_id": "1029", 
      "post_type": "1", 
      "post_text": "bla1", 
     }, 
     { 
      "post_id": "1030", 
      "post_type": "3", 
      "post_text": "bla2", 
     }, 
     { 
      "post_id": "1031", 
      "post_type": "2", 
      "post_text": "bla3",    
     }] 
    } 
} 

我應該如何構建我的陣列才能獲得這個json對不對?

+1

我看不到任何'$了' – Alexander

回答

1

不管怎麼說,這是你應該做的:

... 
$posts = array(); 
foreach ($query->result() as $row) { 
    $post = array(); 
    $post['post_id']   = $row->post_id; 
    $post['post_type']  = $row->post_type; 
    $post['post_text']  = $row->post_text; 
    $posts[] = $post; 
} 
$data['posts'] = $posts; 
... 

的解釋了一下:你必須建立從您從數據庫中獲取信息的對象,這是$post。這些對象中的每一個都需要被添加到一個數組中,即$posts。這個來自數據庫的帖子數組被設置爲$data的密鑰posts,即$data['posts']

0
foreach ($query->result() as $row) { 
    $data['posts']['post_id']   = $row->post_id; 
    $data['posts']['post_type']  = $row->post_type; 
    $data['posts']['post_text']  = $row->post_text; 
} 
1

這個怎麼樣?

http://codepad.viper-7.com/zPHCm0

<?php 
$myData = array(); 
$myData['posts'][] = array('post_id' => 3, 'post_type' => 343, 'post_text' => 'sky muffin pie'); 
$myData['posts'][] = array('post_id' => 4, 'post_type' => 111, 'post_text' => 'Mushroom chocolate banana'); 
$myData['posts'][] = array('post_id' => 231, 'post_type' => 888, 'post_text' => 'Cucumber strawberry in the sky'); 

$theStream['stream'] = $myData; 

$json = json_encode($theStream); 

echo 'JSON:<Br/>'; 
echo $json; 

上面給我:

{ 
    "stream": 
    { "posts":[ 
      {"post_id":3,"post_type":343,"post_text":"sky muffin pie"}, 
      {"post_id":4,"post_type":111,"post_text":"Mushroom chocolate banana"}, 
      {"post_id":231,"post_type":888,"post_text":"Cucumber strawberry in the sky"}] 
    } 
}