1

I have an array of arrays in php called $searchResults. Each array within $searchResults is formatted as such:

array('name' => <name> , 'value' => <value>)

I want to encode this two dimension array as a JSON array and pass it back to my JavaScript. How can I encode this array in PHP such that I can decode it in JavaScript and then iterate through each array by key? Is this even possible? I have found examples of encoding multidimensional arrays that don't use the <key> => <value> syntax but I am not really sure if these are applicable. An example would be here. Thanks!

1
  • 3
    Can you use json_encode? IE: printf( "<script>var jsvar = %s;</script>", json_encode( $searchResults ) ); Commented Sep 18, 2013 at 14:46

2 Answers 2

1

I see two ways:

1) Pass array in current state:

<?php
$array = [
    [ 'name' => 'x' , 'value' => 1 ],
    [ 'name' => 'y' , 'value' => 2 ],
    [ 'name' => 'z' , 'value' => 3 ]
];
?>

<script type="text/javascript">
var php_json = <?php echo json_encode($array); ?>;

for(var i = 0; i < php_json.length; i++){
    console.log(php_json[i]);
}
</script>

2) Convert to key-value pairs and pass:

<?php
$array = [
    [ 'name' => 'x' , 'value' => 1 ],
    [ 'name' => 'y' , 'value' => 2 ],
    [ 'name' => 'z' , 'value' => 3 ]
];

$buffer = [];

foreach($array as &$nested){
    $buffer[$nested['name']] = $nested['value'];
}
?>

<script type="text/javascript">
var php_json = <?php echo json_encode($buffer); ?>;

for(var key in php_json){
     console.log(key, php_json[key]);
     //       key ^      ^ value
}
</script>

You can easily pass any simple php data structure to javascript via using json_encode() function.

Sign up to request clarification or add additional context in comments.

Comments

0

I use this in my templates:

<script>window.bootstrapped_data = <?php echo json_encode($my_js_vars); ?>;</script>

Rendered output will look like this:

<script>window.bootstrapped_data = {"name":"<name>","value":"<value"};</script>

Replace $my_js_vars with your variable name, and called the JavaScript variable whatever you want. You can then access this variable normally in JavaScript.

Don't let json_encode throw you off, PHP will render a valid JavaScript object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.