【问题标题】:How to convert an object from PHP to an Array in Javascript?如何将对象从 PHP 转换为 Javascript 中的数组?
【发布时间】:2016-07-09 15:39:21
【问题描述】:

我正在尝试将从 PHP 获取的对象转换为 Javascript 中的数组,但我不知道如何解决这个问题,我尝试了一些我在做这个问题之前阅读的解决方案,但它不起作用,我在 PHP 中得到了类似的东西

$data = explode(',', $articles);

$length = count($data);

for ($i = 0; $i < $length; $i++) {

    $products = explode('-', $data[$i]);

    $product_key = $products[0];
    $quantity    = $products[1];

   $get_data_product = mysqli_query($connection, "SELECT * FROM articles WHERE id_article = '".$product_key."' AND id_user = '".$id_user."'") or die (mysqli_error($connection));
   $get_data_product = mysqli_fetch_assoc($get_data_product);
   $article_name     = $get_data_product['name'];
   $article_price    = $get_data_product['price'];


   $info[$i] = array('name' => $article_name, 'quantity' => $quantity, 'price' => $article_price);
}

echo json_encode($info);

在 Javascript 中

success: function(info) {

   var data = JSON.stringify(info);

   console.log(data);
}

控制台日志显示这个

[{"name":"prueba 2","quantity":"4","price":"100"}]

我试图用这个代码读取它们,但它只显示数据,只有当我使用控制台日志或警报时

 $.each(data, function(i) {

   $('#content').append('<tr class="text-center">' +
                            '<td>' + data[i].quantity + '</td>' +
                            '<td>' + data[i].name + '</td>' +
                          '</tr>');

});

【问题讨论】:

  • 预期输出是什么?
  • 等等,你为什么要使用 stringify?这会将其更改回字符串。
  • PS:如果您的问题还没有解决,您还需要为我们提供更多的源代码,例如 HTML。好地方@prodigitalson,这在这里很重要
  • @prodigitalson 是的,我解决了删除那部分的问题

标签: javascript php arrays json object


【解决方案1】:

正如 prodigitalson 在 cmets 中指出的那样 - 实际上是答案 - 您将数据转换为 PHP 中的 JSON 对象,但随后将其不必要地转换为字符串,因此您根本无法对其进行操作。

例如:JSON.stringify([{test: 1}]) 变为 "[{test: 1}]"

删除它,您将能够以原始方式循环它,或者您可以使用标准 javascript foreach 循环它,其中data 是您在包含[{"name":"prueba 2","quantity":"4","price":"100"}] 的回调中的响应:

data.forEach(function (e) {
    $('#content').append(
        '<tr class="text-center">\n' +
            '<td>' + e.quantity + '</td>\n' +
            '<td>' + e.name + '</td>\n' +
        '</tr>\n'
    );
});

【讨论】:

  • 这是一个不错的解决方案,比我做的更容易,谢谢
【解决方案2】:

PHP结束示例代码:

<?php 
for ($i = 0; $i < 3; $i++) {
    $quantity=rand(5,10);
    $price=rand(500,1000);
   $info[$i] = array('name' =>'prueba'.$i, 'quantity' =>"$quantity", 'price' => "$price");
}

echo json_encode($info);
?>

JQuery 结束:

<!DOCTYPE html>
<html>
<head>
    <title>Json</title>
     <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
     <script type="text/javascript">
        $(document).ready(function(){
            $.ajax({ type:"POST", url: "array.php",  dataType: "json", success: function(result){
                    console.log(result);
                    for(i=0; i<result.length;i++)
                    {
                        console.log(result[i]);
                        console.log(result[i].name);
                        console.log(result[i].quantity);
                        console.log(result[i].price);
                    }

             }});

        });

     </script>
</head>
<body>

</body>
</html>

测试中的示例响应:

[{"name":"prueba0","quantity":"8","price":"574"},{"name":"prueba1","quantity":"8","price":"555"},{"name"
:"prueba2","quantity":"7","price":"901"}]

参考: http://www.jsoneditoronline.org/?id=5e23cd942a949e86545fa320a65ff0e7

希望这能解决您的问题。谢谢。

【讨论】:

  • result.length 有效吗?因为当我尝试它时它对我不起作用,因为结果是一个对象
  • 您在请求期间没有使用 dataType: "json" ,这不是必需的 var data = JSON.stringify(info); result.length 它给了你计数。谢谢。希望您的问题得到解决。
【解决方案3】:

我认为你的代码很好,如果你在 javascript 代码中这样做:

success: function(info) {

   var data = JSON.stringify(info);

   alert(data[0].name);
}

该警报应显示数据对象名称属性的预期值。

【讨论】:

  • @Vladmir 你的意思是data[0].name
  • @ProfessorZoom 如果你得到正确的回应,你应该可以使用它或[].forEach
  • @IsiahMeadows 但它没有显示任何内容,只是在控制台日志中显示 jquery-1.12.4.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"name":"prueba 2","quantity":"4","price":"100"}] 但除此之外什么都没有
  • 试试Array.prototype.forEach,即info.forEach(function (entry, index) { /* ... */ })
  • 我刚刚注意到,如果我删除 JSON.stringify 部分,它会显示值,那么问题可能出在哪里?
【解决方案4】:

你的 console.log(data);显示 json 数组,即 [{"name":"prueba 2","quantity":"4","price":"100"}]

试试这个

$dataobj = data1=json_decode(data);

$arry = (数组) $dataobj;

试试这个代码

【讨论】:

  • 所以您正试图读取 PHP 代码中的 javascript 变量?
猜你喜欢
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2015-01-13
  • 2011-04-21
  • 2018-03-18
  • 1970-01-01
  • 2015-11-18
相关资源
最近更新 更多