如何向嵌套数组添加其他属性?

时间:2014-08-15 13:10:21

标签: php arrays

如何在将嵌套数组传递给CJSON :: encode()之前添加其他键/值对?

    public static function WS_getAllComments($topic_id){
    $model = ExploreComment::model()->with('user')->findAll(array("condition" => "topic_id = '" . $topic_id . "'"));

    $json = CJSON::encode($model);

    return $json;
}

上面的代码返回一个嵌套数组,看起来像这个

[{"comment_id":"1","user_id":"1","topic_id":"1","data":"This will be my first test comment with 5 stars","image_append":null,"rating":"5","datetime":"2014-08-15 14:36:42"},
{"comment_id":"2","user_id":"2","topic_id":"1","data":"This is another comment with dummy user","image_append":null,"rating":"3","datetime":"2014-08-15 18:00:17"}]

我打算做的是添加一些从相对AR中查询的属性,并将其添加到列表中,如下所示:

[{blablabla, "NewKey":"NewValue"},{blablabla, "NewKey":"NewValue"}]

因此,当我对JSON数据进行编码时,新的键/值对将位于适当的位置...

由于

1 个答案:

答案 0 :(得分:0)

//Convert json to array

$newElement = json_decode('[{"NewKey":"NewValue"},{"NewKey":"NewValue"}]' , true);

//merge array to $model array

$resultArray = array_merge($model, $newElement);

//convert to json
$json = json_encode($model);

return $json;
相关问题