将多层PHP数组转换为Javascript Object Notation

时间:2014-05-29 03:19:03

标签: javascript php ajax

我有一个包含数字索引和键值对的三层PHP数组。我想将其转换为JSON,并通过对象列表重申。我该怎么做? PHP数组名为$main_array,显示为:

Array(
    [0] => Array(
        [STALL JEWELERS] => Array ([0] => 1760 [1] =>2004-03-15)
        [SALEMS JEWELERS] => Array ([0] => 2034 [1] => 2004-02-12)
    )
    [1] => Array(
        [AMBERS DESIGN] => Array ([0] => 300 [1] => 2000-11-15)
        [PINEFOREST] => Array ([0] => 1291 [1] =>2002-06-26)
    )
)

1 个答案:

答案 0 :(得分:2)

您是否尝试过json_encode

echo json_encode($main_array);

应输出

[{"STALL JEWELERS":[1760,"2004-03-15"], "SALEMS JEWLERS":[2034,"2004-02-12"]},
 //second object here
]

要将其添加到您的Javascript中,您需要进行AJAX调用,或者直接将其输出到<script>标记

<script>
var json = <?php echo json_encode($main_array) ?>;
</script>