开发者

Returning PHP Multi-Dimension Array to Javascript/AJAX

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 (bo开发者_StackOverflowth PHP and Javascript code) of this? Lets say we have the two-dim array in PHP:

$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?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜