foreach循环中创建json对象

foreach循环中创建json对象

本文介绍了在php foreach循环中创建json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在php中有以下内容:

I have the following in php:

$follow=explode(" ",$_SESSION['Following']); //create array from the string stored in     session variable

foreach($follow as $val) {
  $show = $val;

    //my query

$result=mysqli_query($dbc,$query);

WHILE ($rows = mysqli_fetch_assoc($result)) {

  //$array[]= $rows; // tried this
  //$array=json_encode($rows); //tried this
  //array_push($array,$rows); // tried this
        }
$json_array=json_encode($array);

    echo $json_array;

如果我一次通过foreach循环,则json对象如下所示:[{key:value} ....],可以在我的JavaScript中进行解析.但是,通过foreach中的多次传递,我得到了多个数组在对象中,如下所示:[{key:value}] [{key:value}] .....结果如下SyntaxError:JSON.parse:JSON数据后出现意外的非空白字符,我猜这是对象内部的[].如何在foreach循环中创建json对象来解决此问题?

If I take a single pass through the foreach loop the json object looks like this:[{key:value}....], which can be parsed in my javascript.However, with multiple passes in the foreach I am getting multiple arrayswithin the object ,like this: [{key:value}][{key:value}]..... which results in the followingSyntaxError: JSON.parse: unexpected non-whitespace character after JSON data, which I guess are the []'s inside the object. How can I create the json object in the foreach loop to fix this?

推荐答案

修复了该问题.我在foreach循环中回显$ json_array.

Fixed it. I was echoing $json_array inside the foreach loop.

这篇关于在php foreach循环中创建json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:37