Convert Multidimensional PHP array to javascript array - php

I'm trying to convert a PHP multidimensional array to a javascript array using the JSON encoder. When I do a var_dump, my php array looks like this:
array (size=2)
'Key' => string 'a' (length=1)
'Value' => string 'asite.com' (length=9)
This is the code I'm currently using in my view to try to convert it to a JavaScript array:
var tempArray = $.parseJSON(<?php echo json_encode($php_array); ?>);
Whenever I run this code in the browser, the output of the conversion in the console is this:
var tempArray = $.parseJSON([{"Key":"a","Value":"asite.com"}]);
Is this the correct structure for a javascript multidimensional array? I'm asking because it keeps giving me this error on the line above:
SyntaxError: Unexpected token o

You do not have to call parseJSON since the output of json_decode is a javascript literal. Just assign it to a variable.
var tempArray = <?php echo json_encode($php_array); ?>;
You should be able then to access the properties as
alert(tempArray[0].Key);

This worked for me.
<script type='text/javascript'>
<?php
$php_array = array(
array("casa1", "abc", "123"),
array("casa2", "def", "456"),
array("casa3", "ghi", "789" )
);
$js_array = json_encode($php_array);
echo "var casas = ". $js_array . ";\n";
?>
alert(casas[0][1]);
</script>

Do not use parseJSON, that's for a string.
Just do:
<?php
$php_array = array ('Key'=>'a', 'Value'=>'asite.com');
?>
<html>
<head>
<script type="text/javascript">
var tempArray = <?php echo json_encode($php_array); ?>;
console.log(tempArray);
</script>
</head>
<body>
</body>
</html>
This give me in the console:
Object { Key="a", Value="asite.com"}

Just add single quotes in the js function,like
var tempArray = $.parseJSON('<?php echo json_encode($php_array); ?>');

Related

Javascript Convert PHP Json into a javascript array

In php I used json_encode(...) and then got the value in Javascript, looks as the following:
["float","float","float","float"] // PS: This is a string...
And I would like to make this into a normal javascript array, like so:
Arr[0] // Will be float
Arr[1] // Will be float
Arr[2] // Will be float
Arr[3] // Will be float
How is this possible?
It sounds like you're retrieving a JSON string in JavaScript (perhaps via AJAX?). If you need to make this into an actual array value, you'd probably want to use JSON.parse().
var retrievedJSON = '["float","float","float","float"]'; // normally from AJAX
var myArray = JSON.parse(retrievedJSON);
If you're actually writing out a value into the page, rather than using AJAX, then you should be able to simply echo the output of json_encode directly, without quoting; JSON itself is valid JavaScript.
var myArray = <?php echo json_encode($myPhpArray); ?>;
var myArray = <?= json_encode($myPhpArray); ?>;
Pretty simple. ;-)
Example:
<?php
$myPhpArray = array('foo', 'bar', 'baz');
?>
<script type="text/javascript">
var myJsArray = <?= json_encode($myPhpArray); ?>;
</script>
Should output (view-source):
<script type="javascript">
var myJsArray = ["foo","bar","baz"];
</script>
Example
I reccomend using jquery. The php file should look as such ...
//location.php
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode($change);
?>
Then the jquery script ...
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>

javascript/php single quote

i'm trying to this:
<?php $php_array = array ('var1' => "l'ape"); ?>
<script type="text/javascript">
var my_javascript_object = jQuery.parseJSON('<?php echo json_encode($php_array); ?>');
</script>
I got this error "Uncaught SyntaxError: Unexpected identifier".
The problem is the single quote in the value of var1 in $php_array.
This doesn't work
<?php $php_array = array ('var1' => "l\'ape"); ?>
You don't need to parse your json with JSON.parse in this case. Just use it as an object literal instead of a Javascript string:
var my_javascript_object = <?php echo json_encode($php_array); ?>;
The problem is that you try to put the JSON in a JavaScript string.
Do this instead:
var my_js_obj = <?php echo json_encode($php_array); ?>;
A JSON string is a valid JavaScript expression which you can simply put directly in your JS code.
If you really wanted to create a string containing JSON (you don't!), you'd do it like this:
var my_json_string = <?php echo json_encode(json_encode($php_array)); ?>;
var my_js_obj = $.parseJSON(my_json_string);

Passing a php array into javascript using JSON

I have a multidimensional array, here:
$noticeDate = json_encode( $noticesDates );
and I want to pass the array into javascript:
var unavailableDates[] = $noticeDate;
Both variables are in the same php file so there is little point using $.getJSON, which basically looks for the variable in an external file. However, how do I pass the object into the javascript array in the same script.
Cheers
You cant directly assign php variables to js, but you can use something like that:
<script>
var unavailableDates = jQuery.parseJSON('<?php echo json_encode($noticeDates) ?>');
</script>
use this
var array = JSON.parse("<?php echo json_encode($noticesDates) ?>");
Try this one:
$.pareseJSON()
here is example:
var json = "<?php echo json_encode($noticesDates); ?>";
jsArray = jQuery.parseJSON(json);

how to read a php array to a java script variable in smarty?

I am getting an array in php, and send it to smarty .tpl file.
In smarty I would like to get that array in a java script variable .
How to do this . Please help me ...
I think it should simple like
<?php
$_array = array('apple','banana','durian');
$js_array = '[' . implode(',',$_array) . ']';
?>
<script type="text/javascript">
var iArray = <?php echo $js_array;?>;
</script>
In php file just add like this
<?
$arr = array(1,2,3,4,5);
$jsarr = implode(',',$arr);
$smarty->assign(arr,$jsarr);
?>
in template file use it like this
<html>
<head>
<script type="text/javascript">
var array = new Array({$arr});
</script>
</head>
</html>
It is better to use [] instead of new Array.
You need to put values in quotes and escape them - to be sure not to break js.
I realy don't like preprocessing data in php just to assign it to smarty.
This solves all potential problems:
<script type="text/javascript">
var arr=[
{foreach name=i from=$myarray item=v}
'{$v|escape:"javascript"}'
{if !$smarty.foreach.i.last},{/if}
{/foreach}
];
</script>
if your array contains only integers the you can use {$v|intval}
Since PHP is parsed prior to any JS, you can simply add the values from the PHP array into a JS function:
So if you have this array in PHP:
$my_array = array("a","b","c","d","e");
Then you can use the following to initialize a JS array with the same values:
<?php
//PHP snippet to create a comma-delimited string with each value of $my_array
//surrounded by quotation marks. Quotes not needed if values in array are numeric.
$array_vals = '"' .implode('","', $my_array) .'"';
?>
<script type="text/javascript">
var my_array = [<?php echo $array_vals;?>];
</script>
The simplest way is to use json:
<script type="text/javascript">
var arr = <?= json_encode($arr) ?>;
</script>
json_encode() takes your php data and converts it into json, and in our case this is exactly what we need.

How to get value to array in javascript

$array = array("1" => "box of chocolates", "2" => "mylar balloons", "3" => "stuffed animals");
<?php
$productWithItem = $array;
foreach ($productWithItem as $pwi) {
?>
<?php echo $pwi->name ?></div>
<?php
}
?>
<script type="text/javascript">
jQuery(function(){
var value_array = ?;
});
</script>
I Want get array value from id="product_name", but I don't know get value from on this javascript, you can help me, thank you
If you are intending to keep your <script> in your html code, build your array in php and use echo:
<script type="text/javascript">
jQuery(function(){
var value_array = <?php echo $yourarray ?>;
});
</script>
That's not an elegant solution, though.
Make product_name as id into class . now $('.product_name') this will be automatically array of objects
example markup
aaa</div>
bb</div>
cc</div>
using each you can extract array
$('.product_name').each(function(){
alert($(this).text());
});
Put your array string in the name attribute of the <a>.
Then you can use jQuery to get it back:
jQuery(function(){
var ele= [YOUR ELEMENT]
var value_array = $.parseJSON($(ele).attr("name"));
});

Categories