【问题标题】:How do I decode json array我如何解码json数组
【发布时间】:2017-04-23 16:27:56
【问题描述】:

我正在使用 ajax 将数据发送到查询 mysql 并返回结果的 php 页面。我的页面中有一个保存 dept 值的变量。但是,如果我 var_dump($_POST) 我看到 var 是一个数组。

如果我在查询中手动输入一个值,则会返回数据。但是,只是不使用我的 $dept var。

如何解码此数组以使该变量可用于我的查询。谢谢

ajax 代码

$.ajax({
   url: 'deptdata.php',
   type: "POST",
   contentType: "application/json; charset=utf-8",
   data: {dept: depts},
   dataType: "json",
      success: function (data) {
        console.log(data);

   },
      error: function (data) {

        alert('error');

        }
      });

在萤火虫标签中发布

dept=DEMOBILL

deptdata.php

<?php

    $dept = $_POST['dept']; <--- array?
    //open connection to mysql db
    $connection = mysqli_connect("localhost","root","","sample") or die("Error " . mysqli_error($connection));

    //fetch table rows from mysql db
    $sql = "select custref from boxes where department = '".$dept."' and status = 1";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

    //create an array
    $emparray = array();
    while($row = mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);

    //close the db connection
    mysqli_close($connection);
?>

【问题讨论】:

  • 你对mysql注入持开放态度,请查看prepared statements
  • 您似乎没有发送任何 json,也不应该发送。不知道为什么要为它设置contentType。显示如何定义 depts
  • 只在本地,所以在上线之前不需要安全
  • 尝试删除contentType 并返回$dept 看看是否符合您的预期。

标签: php jquery json ajax


【解决方案1】:
$myArray = json_decode($data, true);

echo $myArray[0]['id']; // Fetches the first ID
echo $myArray[0]['c_name']; // Fetches the first c_name
// ...
echo $myArray[2]['id']; // Fetches the third ID
// etc..

如果您不将 true 作为第二个参数传递给 json_decode,它会将其作为对象返回:

echo $myArray[0]->id;

【讨论】:

  • 什么是$data
  • json 数据..!! $data = json_decode($json, true);回声 $data[0]["name"]; // "Rishii" $data = json_decode($json);回声$数据[0]->名称; //“利士”
  • 但问题中显示的请求有效负载中没有 json
  • 他使用 json_encode($emparray); 编码成 ...现在它的问题是如何解码 json 数组 .. 就是这样。 !!
  • 那是为了回应!为什么 OP 需要对数组或对象进行编码……然后立即对其进行解码。这完全没有意义。阅读问题。 OP的直接问题与响应无关
猜你喜欢
  • 2015-09-15
  • 2011-02-05
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多