Best method for converting a PHP array to javascript
Use JSON. see why JSON over XML: http://thephpcode.blogspot.com/2008/08/why-json-over-xml-in-ajax.html
To use json in PHP simply:
<?php
echo '<script type="text/javascript">/* <![CDATA[ */';
echo 'var train = '.json_encode($array);
echo '/* ]]> */</script>';
?>
the variable train
in Javascript will be an object containing properties and arrays based on your PHP variable $array
.
To parse or iterate through the train object, you can use for ... in
statements for JSON arrays, and directly use object.property for JSON objects.
See this:
<?php
$array = array(array('id'=>3,'title'=>'Great2'),array('id'=>5,'title'=>'Great'),array('id'=>1,'title'=>'Great3'))
echo '<script type="text/javascript">/* <![CDATA[ */';
echo 'var train = '.json_encode($array);
echo '/* ]]> */</script>';
?>
The output will be:
var train = [{id:3,title:'Great2'},{id:5,title:'Great'},{id:1,title:'Great3'}];
the variable train
becomes an array of objects. [] squrare brackets are arrays, holding more arrays or objects. {} curly braces are objects, they have properties to them.
So to iterate the train
variable:
<script type="text/javascript">
var train = [{id:3,title:'Great2'},{id:5,title:'Great'},{id:1,title:'Great3'}];
for(i in train){
var t = train[i]; // get the current element of the Array
alert(t.id); // gets the ID
alert(t.title); // gets the title
}
</script>
Simple! Hope that really helps.
Convert php array to Javascript
Spudley's answer is fine.
Security Notice: The following should not be necessary any longer for you
If you don't have PHP 5.2 you can use something like this:
function js_str($s)
{
return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}
function js_array($array)
{
$temp = array_map('js_str', $array);
return '[' . implode(',', $temp) . ']';
}
echo 'var cities = ', js_array($php_cities_array), ';';
Pass a PHP array to a JavaScript function
In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:
<script type="javascript">
day = new Array(<?php echo implode(',', $day); ?>);
week = new Array(<?php echo implode(',',$week); ?>);
month = new Array(<?php echo implode(',',$month); ?>);
<!-- Then pass it to the JavaScript function: -->
drawChart(<?php echo count($day); ?>, day, week, month);
</script>
How do I convert php array of array into js array with using .map to reformat
Thank you everyone for your input... It turns out my array coming out of PHP was not an array, but a string that looked like an array... I would like to take credit for this solution, but I was schooled by an awesome architect I know, and he gave me a single line to solve this. All the code you guys provided worked, except my original array was broken so it wasn't a complete fix. Here is the answer.
var myFences = Array.from(<?php echo json_encode($fences)?>).map(e => eval(e).map(p => ({lat:p[0],lng:p[1]})));
console.log(myFences)
This returns a properly formatted array that I can use to create the right output.
Convert PHP array for use in Javascript
something like this should convert your data to the format you are expecting in js:
<?php
$newData = array();
foreach($data as $city=>$values){
$newData[] = array('name'=>$city,'data'=>$values)
}
echo json_encode($newData);
How to convert php array into javascript array to use with the Jquery UI datepicker?
you can use $.parseJSON
function.
<script type="text/javascript">
var unavailabledates = $.parseJSON('<?php echo json_encode($disablethese); ?>');
</script>
<script src="js/datepicker-admin.js"></script>
convert php associative array into javascript object
You can use json_encode() to make array
as an json object
like,
var words = <?php echo json_encode($wordsArray) ?>;// don't use quotes
$.each(words, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
Related Topics
Ssl Error Can Not Change to Tls
Extending Session Timeout in PHP via the .Htaccess
Url Querystring with a PHP Include
Download Multiple Files in One Http Request
How to Get the Shortest Rather Than Longest Possible Regex Match with Preg_Match()
Given an Email as Raw Text, How to Send It Using PHP
Is There a Call_User_Func() Equivalent to Create a New Class Instance
Simulate PHP Array Language Construct or Parse with Regexp
What Does PHP Do with Deprecated Functions
In PHP What Does |= Mean, That Is Pipe Equals (Not Exclamation)
How to Check If Allow_Url_Fopen Is Enabled or Not
How to Put a Translation System in PHP Website
How to Determine the Extension(S) Associated with a Mime Type in PHP