dstd2129 2014-01-17 23:06
浏览 17
已采纳

使用PHP难以使用JSON返回对象

Am I approaching things correctly here? This is what my iOS developer wants me to do for database values for an app he is working on:

{“array”:[{“restID":1, etc.}, {“restID":2, etc.}, {“restID”:3, etc.}, {“restID”:4, etc.}], “error":""}

Right now my PHP code is:

if ($stmt = $mysqli->prepare($query)) {
    $stmt->bind_param("sssisi",$lat,$lat,$lng,$rest_price,$rest_genre,$eat_options);
    $stmt->execute();
    $stmt->bind_result($rest_id,$user_id,$rest_name,$lat,$lng,$rest_price,$rest_rating,$rest_genre,$eat_options,$result);
    //define error array
    $errArray = array('error' => '');
    while ($stmt->fetch()) {
        $row = array(
            'restID' => $rest_id,
            'userID' => $user_id,
            'rest_name' => $rest_name,
            'lat' => $lat,
            'lng' => $lng,
            'restPrice' => $rest_price,
            'restRating' => $rest_rating,
            'restGenre' => $rest_genre,
            'eat_options' => $eat_options);

         $rows['array'][] = $row;
    }
    echo json_encode($rows);
}....

Which outputs the following:

{“array”:[{“restID":1, etc.}, {“restID":2, etc.}, {“restID”:3, etc.}, {“restID”:4, etc.}]}

Notice I can't fit the array in there otherwise I get some crazy stuff or syntax errors with PHP. Please advise! How can I get the first example to work with the current code I am using? What do I need to manipulate in my PHP? Again, I want

{“array”:[{“restID":1, etc.}, {“restID":2, etc.}, {“restID”:3, etc.}, {“restID”:4, etc.}], “error":""}

Not:

{“array”:[{“restID":1, etc.}, {“restID":2, etc.}, {“restID”:3, etc.}, {“restID”:4, etc.}]} 
  • 写回答

3条回答 默认 最新

  • dqb78642 2014-01-17 23:14
    关注

    Just merge the error array into the rows array like so:

    echo json_encode(array_merge($rows, $errArray));

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改