如何访问此JSON编码的php数组的内容?

时间:2013-06-13 13:32:29

标签: php javascript json

我已编辑此问题以反映以下答案。

数组$ animation从另一个函数返回编码,并包含URL的字符串,如index.html,index1.html等。

我使用此功能生成动画..

$select = "SELECT card_id, order_num FROM decks WHERE box_num=$box_num AND id=$userid ORDER BY order_num";
    $result = mysqli_query($db, $select) or die("SQL Error 1: " . mysqli_error($db));

    while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
        $animation[] = array(
            'card_id' => $row['card_id'],
            'order_num' => $row['order_num'],
        );
    }

    return json_encode($animation);

$ animation的内容是

  

“[{” card_id的 “:” 婴儿”, “order_num”: “1”},{ “card_id的”: “selectBaby”, “order_num”: “2”},{ “card_id的”: “床”, “order_num”: “3”},{ “card_id的”: “selectBed”, “order_num”: “4”},{ “card_id的”: “书”, “order_num”: “5”},{ “card_id的”: “selectBook”, “order_num”: “6”},{ “card_id的”: “杯”, “order_num”: “7”},{ “card_id的”: “selectCup”, “order_num”: “8”},{ “card_id的”: “橱柜”, “order_num”: “9”},{ “card_id的”: “selectCupboard”, “order_num”: “10”},{ “card_id的”: “爸爸”, “order_num”:“11 “},{” card_id的 “:” selectDaddy “ ”order_num“: ”12“},{ ”card_id的“: ”吃“, ”order_num“: ”13“},{ ”card_id的“: ”木乃伊“,” order_num “:” 14 “},{” card_id的 “:” selectMummy “ ”order_num“: ”15“},{ ”card_id的“: ”板“, ”order_num“: ”16“},{ ”card_id的“:” selectPlate “ ”order_num“: ”17“},{ ”card_id的“: ”鞋“, ”order_num“: ”18“},{ ”card_id的“: ”selectShoe“, ”order_num“: ”19“},{” card_id的“:” 表”, “order_num”: “20”},{ “card_id的”: “selectTable”, “order_num”: “21”},{ “card_id的”: “行走”, “order_num”: “22”} ,{ “card_id的”: “selectWalking”, “order_num”: “23”},{ “card_id的”: “dogNose”, “order_num”: “24”},{ “card_id的”: “selectDogNose”, “order_num”: “25”},{“卡_id “:” teddyEars”, “order_num”: “26”},{ “card_id的”: “selectTeddyEars”, “order_num”: “27”},{ “card_id的”: “ActivityOne”, “order_num”: “28” },{ “card_id的”: “ActivityTwo”, “order_num”: “29”},{ “card_id的”: “ActivityThree”, “order_num”: “30”},{ “card_id的”: “ActivityFour”, “order_num” : “31”},{ “card_id的”: “ActivityFive”, “order_num”: “32”},{ “card_id的”: “ActivitySix”, “order_num”: “33”}]“

然后我尝试传递javascript。

var url = <?php echo $animation; ?>;
alert(url); //check the for some data

此代码的输出是

  

对象对象对象对象对象对象对象对象   对象

我需要的输出是card_id所以我可以将它传递给网址,例如:婴儿,床,书等

url url url url

我需要字符串才能做到这一点..

$(document).ready(function() {
   var suffix = ".html";
   $('#buffer').load('../Animations/' + url[0] + suffix);
   $('#buffer').trigger('create');    
});

3 个答案:

答案 0 :(得分:2)

您似乎无法在任何地方创建JSON。除非$animation已经是JSON字符串,否则您需要执行此操作:

var jsonUrl = <?php echo json_encode($animation); ?>;

答案 1 :(得分:2)

我假设您有一个有效的json我认为您可以使用json_decode将您的json解码为数组。此函数还支持第三个参数,如果给定为true,则将json作为关联数组返回。

请阅读更多here

答案 2 :(得分:1)

  • 首先,检查<?php echo $animation; ?>是否输出了有效的json 串。
  • 其次,所有浏览器都不支持JSON.parse, 你应该使用像$.parseJSON(来自jquery)
  • 这样的库

在您的情况下,如果您不输出",则根本不需要JSON.parse,因为该对象已经是一个javascript对象。示例:如果<?php echo $animation; ?>呈现为{x:1,y:2}之类的内容,则呈现的javascript就像这样

var jsonUrl = {x:1,y:2};

它已经是一个javascript对象