1

データベースクエリは、次のようにループするいくつかの行を返します。

    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ますか?

4

3 に答える 3

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。データベースからのこの投稿の配列は、のキーに設定されていpostsます。$data$data['posts']

于 2012-09-15T21:28:12.037 に答える
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"}]
    }
} 
于 2012-09-15T21:38:33.657 に答える
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;
}
于 2012-09-15T21:27:41.073 に答える