3

In my PHP-side I have an array of associative arrays like so:

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)
)

I would like to transfer this array to the javascript side. How can I make the javascript counterpart of this array of associative arrays and access the required values?

Basically I want the same functionality as foreach would give me in PHP:

foreach($ArrayOfArrays as $array)
{
  doSomething $array['testName'];
  doSomething $array['created_at'];
}
clentfort
  • 2,454
  • 17
  • 19
jjepsuomi
  • 4,223
  • 8
  • 46
  • 74

1 Answers1

8

All you would have to do essentially is echo out the JavaScript code to the right place on the page.

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

The json_encode() function, returns a JSON representation of a value. JavaScript handles JSON's very easily so you should be able to access your multidimensional array without problems!

Lix
  • 47,311
  • 12
  • 103
  • 131
  • @user1565754 - Happy to help! I'm glad that you found how to "accept" an answer. Voting and accepting peoples posts is the best way to say "thank you" on [so] (if the answer is correct of course) :) – Lix Sep 20 '12 at 11:02
  • :) Yes, I'm a bit new in this so I wasn't quite sure how the protocols work here x) Thnx again! You're doing valuable work for helping others! – jjepsuomi Sep 20 '12 at 11:07