2012-09-20 138 views
3

以我PHP側I有關聯數組的,像這樣的數組:如何將關聯數組的PHP數組轉換爲javascript?

Array (
    [0] => Array (
     [resultId] => 15 
     [testId] => 4 
     [accountId] => 35 
     [score] => 50 
     [standard_deviation] => 0.5 
     [answer_time] => 475.67 
     [created_at] => 2012-09-20 01:45:05 
     [groupId] => 4 
     [accountName] => hbbgrewkcx 
     [testName] => test1), 
    [1] => Array (
     [resultId] => 14 
     [testId] => 3 
     [accountId] => 35 
     [score] => 60 
     [standard_deviation] => 0.5 
     [average_answer_time] => 386.1 
     [created_at] => 2012-09-20 01:44:56 
     [groupId] => 4 
     [accountName] => hbbgrewkcx 
     [testName] => test2) 
) 

我想此陣列傳送到JavaScript端。我怎樣才能使這個關聯數組的數組的JavaScript對應並訪問所需的值?

基本上我想相同的功能的foreach會給我在PHP中:

foreach($ArrayOfArrays as $array) 
{ 
    doSomething $array['testName']; 
    doSomething $array['created_at']; 
} 

回答

8

所有你必須做的基本上是回聲出JavaScript代碼的網頁上的正確位置。

echo "<script language='text/javascript'>"; 
echo "var myArr = ".json_encode($phpArray).";"; 
echo "</script>"; 

json_encode()函數返回值的JSON表示形式。 JavaScript非常容易處理JSON,因此您應該可以毫無問題地訪問多維數組!

+1

你擊敗了我10秒。 – Vlad

+1

感謝您的意見=) – jjepsuomi

+0

@vla - 得到了PHP文檔的書籤;) – Lix

相關問題