2013-03-18 3 views
4

Возможно ли JSON для этого массива php через json_encode? Поскольку этот массив PHP называется $data и когда я делаю ..JSON PHP Array для Javascript

var myJson = <?php echo json_encode($data) ?>; 
console.log(myJson); 

в JavaScript, это дает мне ошибки. Мне было интересно, существует ли ограничение на то, какие типы php-массивов JSON могут/не могут сделать.

Array 
(
    [0] => Array 
     (
      [0] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Tanner, C. kickoff 60 yards to the DU5, Butler, L return 14 yards to the DU19 (Johnson, I.). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => GT35 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 10 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => K 
         ) 

        [drive] => 1 
       ) 

     ) 

    [1] => Array 
     (
      [0] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Renfree, S pass complete to Vernon, C for 6 yards to the DU25 (Thomas, Je.). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU19 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => DU 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 10 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => P 
         ) 

        [drive] => 2 
       ) 

      [1] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Renfree, S pass incomplete to Scott, D. 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU25 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => DU 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 4 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => P 
         ) 

        [drive] => 2 
       ) 

      [2] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Renfree, S pass complete to Scott, D for 6 yards to the DU31, 1ST DOWN DU (Thomas, Je.). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU25 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => DU 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 4 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => P 
         ) 

        [drive] => 2 
       ) 

      [3] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Renfree, S pass complete to Scott, D for no gain to the DU31 (Sweeting, R.). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU31 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => DU 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 10 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => P 
         ) 

        [drive] => 2 
       ) 

      [4] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Renfree, S pass incomplete to Vernon, C. 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU31 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => DU 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 10 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => P 
         ) 

        [drive] => 2 
       ) 

      [5] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Renfree, S sacked for loss of 4 yards to the DU27 (Gotsis, A.). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU31 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => DU 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 10 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => P 
         ) 

        [drive] => 2 
       ) 

      [6] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Monday, W punt 53 yards to the GT20, Golden, J. return 8 yards to the GT28 (Reeves, D). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU27 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => DU 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 14 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => U 
         ) 

        [drive] => 2 
       ) 

     ) 

    [2] => Array 
     (
      [0] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Smith, O. rush for 8 yards to the GT36 (Brown, Ky). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => GT28 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 10 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => R 
         ) 

        [drive] => 3 
       ) 

      [1] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Sims, D. rush for 6 yards to the GT42, 1ST DOWN GT (Sink, N). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => GT36 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 2 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => R 
         ) 

        [drive] => 3 
       ) 

      [2] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Washington, T. pass incomplete to Smith, O.. 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => GT42 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 10 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => P 
         ) 

        [drive] => 3 
       ) 

      [3] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Washington, T. rush for 2 yards to the GT44 (Anunike, K). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => GT42 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 10 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => R 
         ) 

        [drive] => 3 
       ) 

      [4] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Greene, J. rush for 6 yards to the 50 yardline (Canty, W). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => GT44 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 8 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => R 
         ) 

        [drive] => 3 
       ) 

      [5] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Smith, O. rush for 16 yards to the DU34, 1ST DOWN GT (Canty, W;France, C). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => GT50 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 2 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => R 
         ) 

        [drive] => 3 
       ) 

      [6] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Smith, O. rush for 5 yards to the DU29 (France, C). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU34 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 10 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => R 
         ) 

        [drive] => 3 
       ) 

      [7] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Laskey, Z. rush for 3 yards to the DU26 (France, C). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU29 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 5 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => R 
         ) 

        [drive] => 3 
       ) 

      [8] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Washington, T. rush for 3 yards to the DU23, 1ST DOWN GT (France, C). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU26 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 2 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => R 
         ) 

        [drive] => 3 
       ) 

      [9] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Washington, T. pass complete to Smith, O. for 21 yards to the DU2, 1ST DOWN GT (Butler, L). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU23 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 10 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => P 
         ) 

        [drive] => 3 
       ) 

      [10] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Washington, T. rush for 1 yard to the DU1 (Brown, Ky;Foxx, J). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU02 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 0 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => R 
         ) 

        [drive] => 3 
       ) 

      [11] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Washington, T. rush for no gain to the DU1 (Cockrell, R). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU01 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 0 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => R 
         ) 

        [drive] => 3 
       ) 

      [12] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Washington, T. rush for 1 yard to the DU0, TOUCHDOWN, clock 06:51. 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU01 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 0 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => R 
         ) 

        [drive] => 3 
       ) 

      [13] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Tanner, C. kick attempt good. 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => DU03 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 0 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => X 
         ) 

        [drive] => 3 
       ) 

      [14] => Array 
       (
        [text] => SimpleXMLElement Object 
         (
          [0] => Tanner, C. kickoff 54 yards to the DU11, Butler, L return 23 yards to the DU34 (Harrell, A.). 
         ) 

        [spot] => SimpleXMLElement Object 
         (
          [0] => GT35 
         ) 

        [ball] => SimpleXMLElement Object 
         (
          [0] => GT 
         ) 

        [togo] => SimpleXMLElement Object 
         (
          [0] => 0 
         ) 

        [type] => SimpleXMLElement Object 
         (
          [0] => K 
         ) 

        [drive] => 3 
       ) 

     ) 
) 
+0

Вы можете разместить выдаваемый яваскрипт код? – paislee

+0

Вы пытаетесь разобрать PHP на стороне клиента (внутри парсера JavaScript). Это не сработает. Вам нужно запросить массив с помощью POST-вызова с PHP-страницы, иначе это не сработает. – 2013-03-18 23:02:42

+0

Uncaught SyntaxError: Неожиданный токен <@ line var myJson = ; – ealeon

ответ

5

Сначала вам нужен файл PHP на сервере Apache где-нибудь с установленным PHP. Создайте файл, как это:

localhost:8888/myfile.php

<?php 
    $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); 

    echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5} 
?> 

Тогда ваш JavaScript (в этом примере я использую jQuery):

$.getJSON('http://localhost:8888/myfile.php', function(data) { 
    console.log(data); 
}); 

Это должно быть начало, чтобы получить PHP массивы, чтобы ваш JavaScript.

+0

Итак, в этом случае у данных есть мой php-массив? поэтому я смогу получить доступ к массиву, то есть к данным [0] [0] .text в javascript? – ealeon

+0

Да, файл PHP распечатает необработанные «сериализованные/закодированные» данные JSON. JavaScript (jQuery) будет читать исходную строку и декодировать ее обратно в объект 'data' внутри JavaScript. Кодирование/декодирование работает в обоих направлениях. – 2013-03-18 23:21:44

-1

JSON может обрабатывать любой тип массива (хотя он будет отбрасывать ассоциативные массивы в качестве объектов). Проблема, с которой вы, вероятно, сталкиваетесь, заключается в том, что вы пытаетесь выводить с PHP, когда данные доступны только на Javascript.

Чтобы уточнить: после загрузки страницы PHP ничего не может сделать. Только javascript может обрабатывать вещи на стороне клиента, PHP работает только на сервере и не знает состояния клиента.

+0

Это комментарий, а не решение – 2013-03-18 23:06:14

-1

Я никогда не пытался сделать что-то подобное, но я думаю, что у вас проблема, потому что json_encode возвращает строку, закодированную json. Затем вам нужно декодировать эту строку на стороне JavaScript. Попробуйте что-нибудь вроде:

var myJson = JSON.parse(<?php echo json_encode($data) ?>); 
console.log(myJson); 
+0

Idk, почему этот ответ имеет downvotes, но он определенно решил мою проблему. Я получил объект js назад, и когда я Json.stringify, я получил то, что хотел. –

4

Как @Allendar сказал, что вы не можете встроить PHP в JS-файл. Однако вы можете добавить функцию в свой JS-файл для загрузки данных JSON, а затем вставить эти данные в тег скрипта в ваш PHP-файл.

example.js:

var loadJsonFromPHP = function(json) { 
    console.log(json); 
} 

example.php:

<?php 
    $data = array("some", "test", "data"); 
?> 
<html> 
    <head> 
     <script src="example.js"></script> 
     <script> 
      loadJsonFromPHP(<?php echo json_encode($data) ?>); 
     </script> 
    </head> 
    <body></body> 
</html> 

Edit: это при условии, что вам нужно только, чтобы получить данные в JS один раз при загрузке страницы, в этом случае вы можете пропускать запросы AJAX.

+0

Да, но он все еще требует, чтобы файл был PHP-скриптом, запущенным на сервере PHP. Я не уверен, но кажется, что ealeon, похоже, не понимает, как это работает, переплетается. Я надеюсь, что для него что-то получится. :) – 2013-03-18 23:15:12

3

Передача PHP JSON в JavaScript, и чтение

var stuff = <?php print json_encode($datajson); ?>; var arr = new Array(); arr= JSON.parse(stuff); document.write(arr[0].cust_code);