Codeigniter / JSON - 数组结果无效

时间:2014-07-23 00:22:57

标签: php arrays json codeigniter underscore.js

我的代码中有一个奇怪的行为。

下划线模板:

    <% _.each(pinnwand, function(item,key,list) { %>
        <strong>Item: <%= item.name %></strong>
    <% }); %>
    <% _.each(pinnwand2, function(item,key,list) { %>
        <strong>Item: <%= item.name %></strong>
    <% }); %>  

对于阵列&#34; pinnwand&#34;和&#34; pinnwand2&#34;。

阵列:

function getPinnwandData() {
    header('Content-Type: application/json');
    $array = $this->Pinnwand_model->getAllPinnwand($this->input->post('user_id'),"json");
    $data['pinnwand'] = array();
    foreach($array as $a) {
        $data['pinnwand'][] = array("name" => strtolower($a['name']), "id" => $a['id']);
    }
    $data['pinnwand2'] = array(array('name' => 'MettWand',"id" => 1),array('name' => 'wurst2',"id" => 2));
    echo json_encode($data);
}  

奇怪的是,&#34; pinnwand2&#34;显示和&#34; pinnwand&#34;不是。
控制台日志显示:

Object {pinnwand: Array[0], pinnwand2: Array[2]}  

并且数据库中肯定有一些记录&#34; pinnwand&#34;。

这是&#34; Postman&#34; json输出:

{
"pinnwand": [
    {
        "name": "wurst wand",
        "id": "1"
    },
    {
        "name": "schinken wand",
        "id": "2"
    },
    {
        "name": "mett wand ",
        "id": "3"
    }
],
"pinnwand2": [
    {
        "name": "MettWand",
        "id": 1
    },
    {
        "name": "wurst2",
        "id": 2
    }
]

}

我错过了什么?!谢谢!

编辑:
getAllPinnwand方法:

    function getAllPinnwand($userId, $main = "all") {
    if($main == "json") {
        $query = $this->db->get_where('pinnwand', array('user_id' => $userId));
        return $query->result_array();
    } else {
        $query = $this->db->get_where('pinnwand', array('user_id' => $userId));
        $result = $query->result();
        foreach($result as $r) {
            $query1 = $this->db->get_where('pinnwand_content', array('pinnwand_id' => $r->id));
            $r->content  = $query1->result();
        }
        return $result;
    }
}

1 个答案:

答案 0 :(得分:-1)

变化:

foreach($array as $a)
{
    $data['pinnwand'][] = array("name" => strtolower($a['name']), "id" => $a['id']);
}

为:

$csx = count($myarray)

for($x=0;$x<count($myarray);$x++)
{
    $data['pinnwand'][$x] = array("name" => strtolower($myarray[$x]['name']),"id"=>$myarray[$x]['id']);
}

不要在代码中使用保留关键字,例如$ array,只需使用其他名称即可。不要指望PHP正在创造新元素。让循环定义计数器!

看看是否有效......