我學習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"});
注:開閉括號都消失了在上面的輸出。
這工作完美 - 謝謝! – user1176783 2012-02-09 17:20:05
這可能是不可能的,但我會問,除此之外,上面的方法刪除'[]',刪除鍵周圍的引號,但讓它們圍繞值嗎?例如:{「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
@ user1176783你可以用一個正則表達式很容易地做到這一點。嘗試像'preg_replace('/「([^」] +)「:/','$ 1:',trim(json_encode($ requiredFieldsArray),'[]'))' – Paulpro 2012-02-09 18:18:58