2012-02-09 115 views
0

我學習JSON現在已經運行到一個問題:JSON字符串替換

我使用這樣的代碼來吐約和數據的數組:

<?php 
$requiredFieldsArray = array(); 
    $results = mysql_query("select account_id, display_name, id from field 
where account_id = $holdAcctID and required_flag = 1"); 
    while($result = mysql_fetch_assoc($results)) 
     { 
     $requiredFieldsArray[] = $result; 
    } 
?> 
<script language="javascript"> 
    var requiredFieldsPRS = <?php echo "new Array(". json_encode($requiredFieldsArray).")"; ?>; 
</script> 
} 

它輸出這樣的:

var requiedFieldsPRS = new Array([{"account_id":"3","display_name":"Project Requested By","id":"15"},{"account_id":"3","display_name":"Project Title","id":"18"},{"account_id":"3","display_name":"Project Type","id":"19"},{"account_id":"3","display_name":"Banner Details","id":"20"},{"account_id":"3","display_name":"Email to Me","id":"2910"}]);; 

在我的代碼我怎麼能去掉「[「和」]「從數組的開始和結束,所以它會出現這樣的?

var requiedFieldsPRS = new Array({"account_id":"3","display_name":"Project Requested By","id":"15"},{"account_id":"3","display_name":"Project Title","id":"18"},{"account_id":"3","display_name":"Project Type","id":"19"},{"account_id":"3","display_name":"Banner Details","id":"20"},{"account_id":"3","display_name":"Email to Me","id":"2910"}); 

注:開閉括號都消失了在上面的輸出。

回答

0

您可以修剪掉前導和結束[]小號很輕鬆地爲這個特殊的例子:

var requiredFieldsPRS = <?php echo "new Array(". trim(json_encode($requiredFieldsArray), '[]').")"; ?>; 

但是,如果你的數組構造函數是沒有必要的,你可以只用途:

var requiredFieldsPRS = <?php echo json_encode($requiredFieldsArray); ?>; 
+0

這工作完美 - 謝謝! – user1176783 2012-02-09 17:20:05

+0

這可能是不可能的,但我會問,除此之外,上面的方法刪除'[]',刪除鍵周圍的引號,但讓它們圍繞值嗎?例如:{「account_id」:「3」,「display_name」:「Project Requested By」,「id」:「15」}會輸出爲{account_id:「3」,display_name:「Project Requested By」,id: 「15」} – user1176783 2012-02-09 17:55:21

+0

@ user1176783你可以用一個正則表達式很容易地做到這一點。嘗試像'preg_replace('/「([^」] +)「:/','$ 1:',trim(json_encode($ requiredFieldsArray),'[]'))' – Paulpro 2012-02-09 18:18:58

0

嘗試使用JSON_FORCE_OBJECT關鍵

json_encode($requiredFieldsArray,JSON_FORCE_OBJECT); 
+0

這是你的意思:var re quiredFieldsPRS3 = <?php echo json_encode($ requiredFieldsArray,JSON_FORCE_OBJECT);?>;我正在獲取並清空變量結果。 – user1176783 2012-02-09 17:00:45

+0

什麼是您的PHP版本?如果它的<5.3.0,比你不能使用這個選項鍵:) 而是嘗試使用substr像substr(json_encode($ var),1,-1) - 這將刪除方括號 – 2012-02-09 17:13:17