admin管理员组文章数量:1128975
How can I convert a PHP array in a format like this
Array
(
[0] => 001-1234567
[1] => 1234567
[2] => 12345678
[3] => 12345678
[4] => 12345678
[5] => AP1W3242
[6] => AP7X1234
[7] => AS1234
[8] => MH9Z2324
[9] => MX1234
[10] => TN1A3242
[11] => ZZ1234
)
to a Javascript array in the format below?
var cities = [
"Aberdeen",
"Ada",
"Adamsville",
"Addyston",
"Adelphi",
"Adena",
"Adrian",
"Akron",
"Albany"
];
How can I convert a PHP array in a format like this
Array
(
[0] => 001-1234567
[1] => 1234567
[2] => 12345678
[3] => 12345678
[4] => 12345678
[5] => AP1W3242
[6] => AP7X1234
[7] => AS1234
[8] => MH9Z2324
[9] => MX1234
[10] => TN1A3242
[11] => ZZ1234
)
to a Javascript array in the format below?
var cities = [
"Aberdeen",
"Ada",
"Adamsville",
"Addyston",
"Adelphi",
"Adena",
"Adrian",
"Akron",
"Albany"
];
Share
Improve this question
edited Feb 22, 2013 at 22:09
caiosm1005
1,7251 gold badge19 silver badges31 bronze badges
asked Apr 11, 2011 at 8:54
user663878user663878
2,3832 gold badges15 silver badges7 bronze badges
1
|
19 Answers
Reset to default 497I'm going to assume that the two arrays you've given for PHP and JS are not related, and they're just examples of how arrays look in the two languages. Clearly you're not going to be able to convert those sequences of letters and numbers into those city names.
PHP provides a function to convert PHP arrays into Javascript code: json_encode()
. (technically, it's JSON format; JSON stands for JavaScript Object Notation)
Use it like this:
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>
See also the manual page I linked above for more information.
Note that json_encode()
is only available in PHP 5.2 and up, so if you're using an older version, you'll need to use an existing one -- the PHP manual page also includes comments with functions written by people who needed it. (but that said, if you're using anything older than PHP 5.2 you should upgrade ASAP)
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), ';';
Dumb and simple :
var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
You do not have to call parseJSON since the output of json_encode
is a javascript literal. Just assign it to a js variable.
<script type="text/javascript">
//Assign php generated json to JavaScript variable
var tempArray = <?php echo json_encode($php_array); ?>;
//You will be able to access the properties as
alert(tempArray[0].Key);
</script>
you can convert php arrays into javascript using php's json_encode
function
<?php $phpArray = array( 0 => 001-1234567, 1 => 1234567, 2 => 12345678, 3 => 12345678, 4 => 12345678, 5 => 'AP1W3242', 6 => 'AP7X1234', 7 => 'AS1234', 8 => 'MH9Z2324', 9 => 'MX1234', 10 => 'TN1A3242', 11 => 'ZZ1234' ) ?>
<script type="text/javascript">
var jArray= <?php echo json_encode($phpArray ); ?>;
for(var i=0;i<12;i++){
alert(jArray[i]);
}
</script>
Is very simple I use this way:
JAVASCRIPT:
var arrayJavascript = <?php echo json_encode($arrayPhp) ?>;
Convert PHP array to Javascript
Regards!
I find the quickest and easiest way to work with a PHP array in Javascript is to do this:
PHP:
$php_arr = array('a','b','c','d');
Javascript:
//this gives me a JSON object
js_arr = '<?php echo JSON_encode($php_arr);?>';
//Depending on what I use it for I sometimes parse the json so I can work with a straight forward array:
js_arr = JSON.parse('<?php echo JSON_encode($php_arr);?>');
u can also do in this way
<script>
<?php
$php_array = array('abc','def','ghi');
?>
var array_code = <?php echo json_encode($php_array); ?>;
console.log(array_code);
</script>
so simple ...!
use this method:
<?php echo json_encode($your_array); ?>;
in laravel blade {{ }} use this method:
{{ str_replace('"', '', json_encode($your_array)) }}
working for associated and unassociated array.
This is my function. JavaScript must be under PHP otherwise use SESSION.
<?php
$phpArray=array(1,2,3,4,5,6);
?>
<div id="arrayCon" style="width:300px;"></div>
<script type="text/javascript">
var jsArray = new Array();
<?php
$numArray=count($phpArray);
for($i=0;$i<$numArray;$i++){
echo "jsArray[$i] = ". $phpArray[$i] . ";\n";
}
?>
$("#arrayCon").text(jsArray[1]);
</script>
Last row can be ....text(jsArray); and will be shown "1,2,3,4,5,6"
For a multidimensional array in PHP4 you can use the following addition to the code posted by Udo G:
function js_str($s) {
return '"'.addcslashes($s, "\0..\37\"\\").'"';
}
function js_array($array, $keys_array) {
foreach ($array as $key => $value) {
$new_keys_array = $keys_array;
$new_keys_array[] = $key;
if(is_array($value)) {
echo 'javascript_array';
foreach($new_keys_array as $key) {
echo '["'.$key.'"]';
}
echo ' = new Array();';
js_array($value, $new_keys_array);
} else {
echo 'javascript_array';
foreach($new_keys_array as $key) {
echo '["'.$key.'"]';
}
echo ' = '.js_str($value).";";
}
}
}
echo 'var javascript_array = new Array();';
js_array($php_array, array());
I use a fake php array
<?php
// instead to create your array like this
$php_array = ["The","quick","brown","fox","jumps","over","the","lazy","dog"];
// do it like this (a simple variable but with separator)
$php_fake_array = "The,quick,brown,fox,jumps,over,the,lazy,dog";
?>
<script type="text/javascript">
// use the same separator for the JS split() function
js_array = '<?php echo $php_fake_array; ?>'.split(',');
</script>
if ever your array is unknown (already made)
<?php
$php_array = file('my_file.txt');
$php_fake_array = "";
// transform your array with concatenate like this
foreach ($php_array as $cell){
// since this array is unknown, use clever separator
$php_fake_array .= $cell.",,,,,";
}
?>
<script type="text/javascript">
// use the same separator for the JS split() function
js_array = '<?php echo $php_fake_array; ?>'.split(',,,,,');
</script>
I had the same problem and this is how i done it.
/*PHP FILE*/
<?php
$data = file_get_contents('http://yourrssdomain.com/rss');
$data = simplexml_load_string($data);
$articles = array();
foreach($data->channel->item as $item){
$articles[] = array(
'title' => (string)$item->title,
'description' => (string)$item ->description,
'link' => (string)$item ->link,
'guid' => (string)$item ->guid,
'pubdate' => (string)$item ->pubDate,
'category' => (string)$item ->category,
);
}
// IF YOU PRINT_R THE ARTICLES ARRAY YOU WILL GET THE SAME KIND OF ARRAY THAT YOU ARE GETTING SO I CREATE AN OUTPUT STING AND WITH A FOR LOOP I ADD SOME CHARACTERS TO SPLIT LATER WITH JAVASCRIPT
$output="";
for($i = 0; $i < sizeof($articles); $i++){
//# Items
//| Attributes
if($i != 0) $output.="#"; /// IF NOT THE FIRST
// IF NOT THE FIRST ITEM ADD '#' TO SEPARATE EACH ITEM AND THEN '|' TO SEPARATE EACH ATTRIBUTE OF THE ITEM
$output.=$articles[$i]['title']."|";
$output.=$articles[$i]['description']."|";
$output.=$articles[$i]['link']."|";
$output.=$articles[$i]['guid']."|";
$output.=$articles[$i]['pubdate']."|";
$output.=$articles[$i]['category'];
}
echo $output;
?>
/* php file */
/*AJAX COMUNICATION*/
$(document).ready(function(e) {
/*AJAX COMUNICATION*/
var prodlist= [];
var attrlist= [];
$.ajax({
type: "get",
url: "php/fromupnorthrss.php",
data: {feeding: "feedstest"},
}).done(function(data) {
prodlist= data.split('#');
for(var i = 0; i < prodlist.length; i++){
attrlist= prodlist[i].split('|');
alert(attrlist[0]); /// NOW I CAN REACH EACH ELEMENT HOW I WANT TO.
}
});
});
I hope it helps.
Keep it simple :
var jsObject = JSON.parse('<?= addslashes(json_encode($phpArray)) ?>');
Many good and complex solutions are here and this is a way to doing it without parsing json in user side.
$mtc=array();
$replace=array();
$x = json_encode($thearray);
preg_match_all('/"[a-z0-9_]*":/',$x,$mtc);
foreach($mtc[0] as $v){
array_push($replace,str_replace('"','',$v));
}
$x = str_replace($mtc[0],$replace,$x);
echo '<script type="text/javascript">x='.$x.';console.log(x);</script>';
This works with both indexed and associative arrays(any combination) which has multiple levels, and no need for user side json parsing.
for php use this :
var js_array = <?php echo json_encode($php_array); ?>;
for blade use this:
var js_array = {{ Js::from($php_array) }};
or simply use this:
var js_array @json($php_array)
docs : https://laravel.com/docs/10.x/blade#rendering-json
If you need a multidimensional PHP array to be printed directly into the html page source code, and in an indented human-readable Javascript Object Notation (aka JSON) fashion, use this nice function I found in http://php.net/manual/en/function.json-encode.php#102091 coded by somebody nicknamed "bohwaz".
<?php
function json_readable_encode($in, $indent = 0, $from_array = false)
{
$_myself = __FUNCTION__;
$_escape = function ($str)
{
return preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str);
};
$out = '';
foreach ($in as $key=>$value)
{
$out .= str_repeat("\t", $indent + 1);
$out .= "\"".$_escape((string)$key)."\": ";
if (is_object($value) || is_array($value))
{
$out .= "\n";
$out .= $_myself($value, $indent + 1);
}
elseif (is_bool($value))
{
$out .= $value ? 'true' : 'false';
}
elseif (is_null($value))
{
$out .= 'null';
}
elseif (is_string($value))
{
$out .= "\"" . $_escape($value) ."\"";
}
else
{
$out .= $value;
}
$out .= ",\n";
}
if (!empty($out))
{
$out = substr($out, 0, -2);
}
$out = str_repeat("\t", $indent) . "{\n" . $out;
$out .= "\n" . str_repeat("\t", $indent) . "}";
return $out;
}
?>
Below is a pretty simple trick to convert PHP array to JavaScript array:
$array = array("one","two","three");
JS below:
// Use PHP tags for json_encode()
var js_json = json_encode($array);
var js_json_string = JSON.stringify(js_json);
var js_json_array = JSON.parse(js_json_string);
alert(js_json_array.length);
It works like a charm.
For Laravel user: use @json
var cities = @json($data);
As explained in official docs: https://laravel.com/docs/8.x/blade#rendering-json:
本文标签: Convert php array to JavascriptStack Overflow
版权声明:本文标题:Convert php array to Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736702521a1948501.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
script
tag that will create it, or are you trying to create JSON to send back in reply to an ajax request, or... (Also, worth checking out the How to Format box on the right-hand side when you're asking your question, and the page linked from the [?] just above the question area.) – T.J. Crowder Commented Apr 11, 2011 at 8:56