2012-02-15 77 views
0

我想返回PHP token_get_all()函数作为JSON。PHP json_encode token_get_all

我也希望token_get_all传递令牌通过token_name()函数来获得它的名字。

我尝试了各种不同的方法,但没有产生我需要的结果。

我想要在JavaScript中使用这些信息,例如我想能够调用tokens.tokenName。

我想我需要像下面的例子:

{ 

"tokenName":"T_COMMENT","tokenValue":"# some comment","tokenLine":"1" 
"tokenName":"T_VARIABLE","tokenValue":"$some_variable","tokenLine":"2" 
} 

我试图直接通过json_encode()功能把token_get_all()函数,以及与不同的阵列玩耍,结果不是我想要的。

这是代码的最新的化身:

if (isset($_POST['code']) || (isset($_GET['code']))) { 

    if (isset($_POST['code'])) { 
     $code = $_POST['code']; 
    } elseif (isset($_GET['code'])) { 
     $code = $_GET['code']; 
    } 

    $tokens = array(); 
    $tokenName = array(); 
    $tokenValue = array(); 
    $tokenLine = array(); 

    foreach(token_get_all($code) as $c) { 

     if(is_array($c)) { 
      array_push($tokenName, token_name($c[0])); // token name 
      array_push($tokenValue, $c[1]); // token value 
      array_push($tokenLine, $c[2]); // token line number 

     } else { 
      array_push($tokenValue, $c); // single token, no value or line number 
     } 

    } 

    // put our token into the tokens array 
    array_push($tokens, $tokenName); 
    array_push($tokens, $tokenValue); 
    array_push($tokens, $tokenLine); 

    // return our tokens array JSON encoded 
    echo(json_encode($tokens)); 


} 

谢谢

瑞安

回答

2

我猜你真正想要做的是生成字典的列表。对于你应该更喜欢普通的数组,而不是附加的array_push

foreach(token_get_all($code) as $c) { 

    $tokens[] = 
     array(
      "tokenName" => token_name($c[0]), 
      "tokenValue" => $c[1], 
      "tokenLine" => $c[2] 
     ); 

} 

为您节省一些临时变量,更容易阅读。它会给你一个结果,如:

[  
    {"tokenName":"T_COMMENT","tokenValue":"# some comment","tokenLine":"1"}, 
    {"tokenName":"T_VARIABLE","tokenValue":"$some_variable","tokenLine":"2"} 
] 
+0

谢谢你,这似乎很好。 :) – ethicalhack3r 2012-02-16 11:19:59