将PHP多维数组返回给Javascript/AJAX

时间:2022-03-30 21:36:03

My understanding is that in order to return a complex PHP variable to Javascript, it should be done via AJAX and json_encode. Could somebody give me an actual example (both PHP and Javascript code) of this? Lets say we have the two-dim array in PHP:

我的理解是,为了将复杂的PHP变量返回到Javascript,应该通过AJAX和json_encode实现。有人能给我一个实际的例子(PHP和Javascript代码)吗?让我们说,我们在PHP中有两个dim数组:

$twoDArr = array( array('Greg', 44, 'Owner'),
                  array('Joe', 23, 'Renter'),
                  array('Susan', 39, 'Owner'),
                  array('John', 32, 'Renter)
                );

How would we return this to an analogous two dimensional array in javascript using json_encode?

如何使用json_encode将它返回到javascript中类似的二维数组中呢?

2 个解决方案

#1


2  

<?php

$twoDArr = array( array('Greg', 44, 'Owner'),
                  array('Joe', 23, 'Renter'),
                  array('Susan', 39, 'Owner'),
                  array('John', 32, 'Renter)
                );
?>

<script>
twoDArr = JSON.parse(<?=json_encode($twoDArr)?>)
alert(twoDArr[0][0]) //alerts 'Greg'
alert(twoDArr[0][1]) //alerts '44'
alert(twoDArr[1][0]) //alerts 'Joe'
</script>

#2


0  

Your program would of ran in a more simpler way like this:

你的程序会以更简单的方式运行:

        <?php

            $twoDArr = array( array('Greg', 44, 'Owner'),
                              array('Joe', 23, 'Renter'),
                              array('Susan', 39, 'Owner'),
                              array('John', 32, 'Renter)
                            );
        ?>

        <script>
            var twoDArr = <?php echo json_encode($twoDArr); ?>;
            alert(twoDArr[0][0]) //alerts 'Greg'
            alert(twoDArr[0][1]) //alerts '44'
            alert(twoDArr[1][0]) //alerts 'Joe'
        </script>

#1


2  

<?php

$twoDArr = array( array('Greg', 44, 'Owner'),
                  array('Joe', 23, 'Renter'),
                  array('Susan', 39, 'Owner'),
                  array('John', 32, 'Renter)
                );
?>

<script>
twoDArr = JSON.parse(<?=json_encode($twoDArr)?>)
alert(twoDArr[0][0]) //alerts 'Greg'
alert(twoDArr[0][1]) //alerts '44'
alert(twoDArr[1][0]) //alerts 'Joe'
</script>

#2


0  

Your program would of ran in a more simpler way like this:

你的程序会以更简单的方式运行:

        <?php

            $twoDArr = array( array('Greg', 44, 'Owner'),
                              array('Joe', 23, 'Renter'),
                              array('Susan', 39, 'Owner'),
                              array('John', 32, 'Renter)
                            );
        ?>

        <script>
            var twoDArr = <?php echo json_encode($twoDArr); ?>;
            alert(twoDArr[0][0]) //alerts 'Greg'
            alert(twoDArr[0][1]) //alerts '44'
            alert(twoDArr[1][0]) //alerts 'Joe'
        </script>