简体   繁体   中英

Codeigniter / JSON - array result invalid

I have a strange behaviour in my code.

Underscore template:

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

for the array "pinnwand" and "pinnwand2".

Arrays:

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);
}  

Strange thing is, "pinnwand2" is displaying and "pinnwand" not.
Console log shows this:

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

and there are definitely some records in the database for "pinnwand".

this is the "Postman" json output:

{
"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
    }
]

}

what am I missing?! Thanks!

EDIT:
getAllPinnwand method:

    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;
    }
}

change:

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

to:

$csx = count($myarray)

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

Don't use reserved keywords like $array in code, just take other names. Don't expect that PHP is creating new elements. Just let the loop define the counter!

Look if that works....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM