dongre6404 2016-12-16 07: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-16 07:15
    关注

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

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

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?