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

时间:2016-07-09 15:39:22

标签: javascript php arrays json object

我试图将我从PHP获得的对象转换为Javascript中的数组,但我不知道如何解决这个问题,我尝试了一些解决方案之前我已经阅读了这个问题,但它并没有&# 39; t work,我在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>');

});

4 个答案:

答案 0 :(得分:2)

正如prodigitals在评论中注意到的 - 实际上是答案 - 你在PHP中将数据转换为JSON对象,然后将其不必要地转换为字符串,这样你就无法操纵它。 / p>

例如: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'
    );
});

答案 1 :(得分:2)

PHP结束示例代码:

{
  "response": {
    "status":"ok",
    "userTier":"developer",
    "total":1869990,
    "startIndex":1,
    "pageSize":10,
    "currentPage":1,
    "pages":186999,
    "orderBy":"newest",
    "results":[
      {
        "id":"sport/live/2016/jul/09/tour-de-france-2016-stage-eight-live",
         "type":"liveblog",
         "sectionId":"sport",
         "sectionName":"Sport",
         "webPublicationDate":"2016-07-09T13:21:36Z",
         "webTitle":"Tour de France 2016: stage eight – live!",
         "webUrl":"https://www.theguardian.com/sport/live/2016/jul/09/tour-de-france-2016-stage-eight-live",
         "apiUrl":"https://content.guardianapis.com/sport/live/2016/jul/09/tour-de-france-2016-stage-eight-live",
         "isHosted":false
       },
       {
         "id":"sport/live/2016/jul/09/serena-williams-v-angelique-kerber-wimbledon-womens-final-live",
         "type":"liveblog",
         "sectionId":"sport",
         "sectionName":"Sport",
         "webPublicationDate":"2016-07-09T13:21:02Z",
         "webTitle":"Serena Williams v Angelique Kerber: Wimbledon women's final – 
...

JQuery End:

<?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);
?>

测试中的示例响应:

<!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>

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

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

答案 2 :(得分:1)

我认为您的代码很好,如果您在javascript代码中执行此操作:

success: function(info) {

   var data = JSON.stringify(info);

   alert(data[0].name);
}

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

答案 3 :(得分:1)

你的console.log(数据);显示json arry即是 [{“name”:“prueba 2”,“quantity”:“4”,“price”:“100”}]

试试这个

$ dataobj = data1 = json_decode(data);

$ arry =(array)$ dataobj;

试试这段代码