dongre6404 2016-12-15 23:11
浏览 60
已采纳

删除每次迭代后添加的extra []以通过PHP发送JSON

public function  showcarts($email){
    $sql = 'SELECT * FROM users WHERE email = :email';
    $query0 = $this -> conn -> prepare($sql);
    $query0 -> execute(array(':email' => $email));
    $data = $query0 -> fetchObject();
    $p_cart= $data -> p_cart;  
    $p_cart = preg_replace('/\.$/', '', $p_cart); //Remove dot at end if exists
    $array = explode(',', $p_cart); //split string into array seperated by ', '
    $projects=array();
    foreach($array as $p_id) //loop over values
    {   
        $sql = 'SELECT * FROM products WHERE p_id = :p_id';
        $query = $this -> conn -> prepare($sql);
        $query -> execute(array(':p_id' => $p_id)); 
        if($query){
            while($products = $query -> fetchAll(PDO::FETCH_OBJ))
            {
                 array_push($projects,$products);
            }
        }         
    }
    return $projects;   
}

enter image description here

This function is returning the objects as required but adding [] after every iteration. I want to remove the extra [] so that it can fit to my modal object. Is there a way to do this ?

  • 写回答

1条回答 默认 最新

  • dousonghs58612 2016-12-15 23:15
    关注

    fetchAll fetches all rows immediately, so it's redundant to use while:

    if($query){
        $projects = $query -> fetchAll(PDO::FETCH_OBJ);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部