Javascript 将 JSON 从 PHP 返回到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11994896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:57:43  来源:igfitidea点击:

Returning JSON from PHP into Array

phpjavascriptjsonjquery

提问by KraigBalla

I want to take the returning JSON object and display what the PHP query returned, but when I use brackets to access the indices value it displays only one character at a time. Basically I want each index to contain each row from the query. This particular query has two results (the id and file name). I would like to get both the id and name into one index of the JSON array. Output displayed below:

我想获取返回的 JSON 对象并显示 PHP 查询返回的内容,但是当我使用括号访问索引值时,它一次只显示一个字符。基本上我希望每个索引都包含查询中的每一行。这个特定的查询有两个结果(id 和文件名)。我想将 id 和 name 都放入 JSON 数组的一个索引中。输出显示如下:

7 5.jpg
8 7-mini.jpg

Here is my code...

这是我的代码...

<script type="text/javascript">

  $(function(){
    $.ajax({                                      
      url: '<?php echo base_url().'jqueryDB/jquery';?>',   
      type:'POST',      
      dataType: 'json',    
      success: function(output_string){
                document.write(output_string[0]);
      }
    });

  }); 

Right now this display '7', instead of '7 5.jpg'. How can I get it to store each row into one index?

现在这个显示'7',而不是'7 5.jpg'。如何让它将每一行存储到一个索引中?

Here's my PHP file:

这是我的 PHP 文件:

    $userID = $this->session->userdata('id');   
    $query = $this->db->query('SELECT * FROM upload WHERE userID = '.$userID);
    $num_rows = $query->num_rows();
    $val = $query->row_array();    

    $output_string = "";  

    foreach ($query->result() as $row){
        $output_string .= $row->id;
        $output_string .= " ".$row->name."<br />";
    }

    echo json_encode($output_string);

回答by David Fells

...
$output = array();
foreach ($query->result() as $row) {
  $output[] = $row->id . ' ' . $row->name;
}
echo json_encode($output);

回答by Jeff Lambert

First, you want to store the results of your query into an array, nota string. The results of calling json_encodewill take that array and turn it into a JSON-encoded string.

首先,您希望将查询结果存储到一个数组中,而不是一个字符串中。调用的结果json_encode将采用该数组并将其转换为 JSON 编码的字符串。

$output_array = array();

foreach($query->result() as $row) {
    $output_array[] = array( 'id' => $row->id, 'name' => $row->name );
}

echo json_encode( $output_array );

Notice that the array you pass it can be arbitrarily deep. json_encodewill structure the object based off of the structure of the array. I would also suggest looking at the resultant string in your browser to see what the JSON looks like when encoding multidimensional arrays like this.

请注意,您传递给它的数组可以任意深。 json_encode将根据数组的结构构造对象。我还建议在您的浏览器中查看结果字符串,以了解在对这样的多维数组进行编码时 JSON 的样子。

In your javascript, you must parsethe string to get it to be a useful JavaScript object...

在您的 javascript 中,您必须解析字符串以使其成为有用的 JavaScript 对象...

success: function(output_string){
    var obj = JSON.parse( output_string );
    // This will iterate over all of the values in the return object
    for(var i in obj) {
        document.write(obj[i].name + '<br>' + obj[i].id);
    }
}

Feel free to structure your return object differently, I was just going off of what you laid out in your question.

随意以不同的方式构造您的返回对象,我只是从您在问题中提出的内容出发。

jQuery also has facilities where, if you specify your MIME types correctly, the parameter to your successcallback will automatically be parsed into a JSON object for you. For more information see the jQuery documentation

jQuery 还具有一些功能,如果您正确指定了 MIME 类型,success回调的参数将自动为您解析为 JSON 对象。有关更多信息,请参阅jQuery 文档

回答by Gabe Spradlin

I wrote most of this before @watcher's answer came up and it's probably the one you want but this was written already so I figured I post it. I'd modify @David Fells solution like this:

我在@watcher 的回答出现之前写了大部分内容,这可能是你想要的,但已经写好了,所以我想我把它贴出来。我会像这样修改@David Fells 解决方案:

$output = array();
foreach ($query->result() AS $row) {
  $output[$row->id] = array();

  foreach ($row AS $prop=>$value) {
    $output[$row->id][$prop] = $value;
  }
}

$output_json = json_encode($output);

I generally use PDO objects for accessing my DBs and that returns an array instead of object. This should work for an array but I believe it will work with objects in PHP as well.

我通常使用 PDO 对象来访问我的数据库并返回一个数组而不是对象。这应该适用于数组,但我相信它也适用于 PHP 中的对象。

This should work with any query that returns a column named id and obviously the id portion could be replaced with $id where $id equals whatever id string/integer you'd like use.

这应该适用于任何返回名为 id 的列的查询,显然可以用 $id 替换 id 部分,其中 $id 等于您想要使用的任何 id 字符串/整数。

...

...

Now when you want the array back in PHP (I'm not particularly familiar with javascript) you would need to use:

现在,当您想要在 PHP 中返回数组时(我对 javascript 不是特别熟悉),您需要使用:

// The TRUE returns it as an array rather than object.
$output = json_decode($output_json, TRUE);

Much of this is pretty basic and I imagine you know it already. But the title made me think that the this last part - the json_decode part - was what you needed and maybe it will help someone else who finds this question.

其中大部分内容非常基本,我想您已经知道了。但是标题让我觉得最后一部分 - json_decode 部分 - 是你需要的,也许它会帮助发现这个问题的其他人。