How to pass php array into javascript array without JSON?

Here’s my php array. This array is generated by var_dump of $events.
array(3) {
[0]=> array(1) {
[“Event”]=> array(5) {
[“id”]=> string(3) “102”
[“headline”]=> string(31) “Concert in the Park”
[“message”]=> string(44) “The Band will be playing in the park on Saturday night”
[“close_date”]=> string(10) “2012-06-17”
[“start_date”]=> string(10) “2012-06-16”
} }

[1]=> array(1) {
[“Event”]=> array(5) {
[“id”]=> string(3) “102”
[“headline”]=> string(31) “Comedy Night”
[“message”]=> string(44) “Friday night comedy at Downtown Club”
[“close_date”]=> string(10) “2012-06-15”
[“start_date”]=> string(10) “2012-06-15”
} }

[2]=> array(1) {
[“Event”]=> array(5) {
[“id”]=> string(3) “102”
[“headline”]=> string(31) “Fireworks Show”
[“message”]=> string(44) “There will be a fireworks show after the baseball game”
[“close_date”]=> string(10) “2012-07-4”
[“start_date”]=> string(10) “2012-07-4”
} }
}
was going to do a foreach $events as $event then
need to put $event[‘Event’][‘headline’] - $event[‘Event’][‘message’]

in place of “Message 1”, “Message 2” and so on in javascript array:
$(function() {

$foo({
“messages”: [“Message 1”, “Message 2”, “Message 3”, “Message 4”, “Message 5”]
}
});

Why can you not use JSON?

I’m not sure. Just trying to keep the solution simple.

For php:

$out = json_encode( $events );

For Javascript:

var events = JSON.parse( phpout );

Simple. (For old browsers that don’t have native support for JSON: https://github.com/douglascrockford/JSON-js)

Thanks! I assume that grabs my entire array but I need to grab only the ‘headline’ and ‘message’ and I don’t understand how any of it would populate my javascript array, “messages” within my function. As you may have guessed I am not familiar with js.

You use JSON to pass data between PHP and Javascript via AJAX, but if you’re just outputting PHP and need to pass it into JS, you can literally echo it.


<?php
    $var = 'hi';
    echo "<script>";
    echo "var js_var = '$var';";
    echo "</script>";
?>

Then the resulting HTML looks like this <script> var js_var = ‘hi’; </script>

I have 3 events from my array up above where I need key [0] to replace “Message 1” in my js array, key [1] to replace “Message 2” and key [2] to replace “Message 3” and so on. The amount of events may change. JSON only complicates the matter because I don’t know it or how to use it. Since I don’t know how to get php into js, getting JSON to js seems like more work. I am not able to change the call to “messages” within my js function. They need to be within the [ and double quotes and separated by a comma. Thanks for looking.