如何在 Javascript 中将对象从 PHP 转换为数组

How to convert an object from PHP to an Array in Javascript?

本文关键字:PHP 转换 数组 对象 Javascript      更新时间:2023-09-26

我正在尝试将从 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>');
});

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

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

删除它,

您将能够以原始方式循环它,或者您可以使用标准的 javascript for each 循环它,其中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'
    );
});

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

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

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

success: function(info) {
   var data = JSON.stringify(info);
   alert(data[0].name);
}

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

你的控制台.log(data); 显示 json arry 那是[{"名称":"普鲁巴 2","数量":"4","价格":"100"}]

试试这个

$dataobj = 数据1=json_decode(数据);

$arry = (数组) $dataobj;

试试这个代码