将 php 数组转换为 Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5618925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:04:35  来源:igfitidea点击:

Convert php array to Javascript

phpjavascriptarrays

提问by user663878

How can I convert a PHP array in a format like this

如何以这样的格式转换 PHP 数组

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?

到以下格式的 Javascript 数组?

var cities = [
    "Aberdeen",
    "Ada",
    "Adamsville",
    "Addyston",
    "Adelphi",
    "Adena",
    "Adrian",
    "Akron",
    "Albany"
];

采纳答案by Udo G

Spudley's answer is fine.

Spudley 的回答很好

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:

如果你没有 PHP 5.2,你可以使用这样的东西:

function js_str($s)
{
    return '"' . addcslashes($s, "
<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>
..\"\") . '"'; } function js_array($array) { $temp = array_map('js_str', $array); return '[' . implode(',', $temp) . ']'; } echo 'var cities = ', js_array($php_cities_array), ';';

回答by Spudley

I'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 和 JS 提供的两个数组不相关,它们只是数组在两种语言中的外观示例。显然,您无法将这些字母和数字序列转换为城市名称。

PHP provides a function to convert PHP arrays into Javascript code: json_encode(). (technically, it's JSON format; JSON stands for JavaScript Object Notation)

PHP 提供了一个将 PHP 数组转换为 Javascript 代码的函数:json_encode(). (从技术上讲,它是 JSON 格式;JSON 代表 JavaScript Object Notation)

Use it like this:

像这样使用它:

var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];

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)

请注意,json_encode()它仅在 PHP 5.2 及更高版本中可用,因此如果您使用的是旧版本,则需要使用现有版本——PHP 手册页还包括由需要它的人编写的函数注释。(不过话说回来,如果你使用的是 PHP 5.2 之前的版本,你应该尽快升级)

回答by Eric

Dumb and simple :

愚蠢而简单:

<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>

回答by Jaykishan

You do not have to call parseJSON since the output of json_encodeis a javascript literal.Just assign it to a js variable.

您不必调用 parseJSON,因为 的输出json_encode是 javascript 文字。只需将它分配给一个 js 变量。

<?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'
    )
?>

回答by Dipesh KC

you can convert php arrays into javascript using php's json_encodefunction

您可以使用 php 的json_encode函数将 php 数组转换为 javascript

<?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>
$php_arr = array('a','b','c','d');

回答by user3065931

I find the quickest and easiest way to work with a PHP array in Javascript is to do this:

我发现在 Javascript 中使用 PHP 数组的最快和最简单的方法是这样做:

PHP:

PHP:

//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);?>');

Javascript:

Javascript:

<?php echo json_encode($your_array); ?>; 

回答by ??????? ????

so simple ...!

很简单 ...!

use this method:

使用这个方法:

{{ str_replace('&quot;', '', json_encode($your_array)) }} 

in laravel blade {{ }}use this method:

在 Laravel Blade {{ }} 中使用此方法:

<script>  
    <?php 
        $php_array = array('abc','def','ghi');
        $code_array = json_encode($php_array);
    ?>  
    var array_code = <?php echo $code_array; ?>;
    console.log(array_code);
</script>

working for associated and unassociated array.

为关联和非关联数组工作。

回答by cool Quazi

u can also do in this way

你也可以这样做

function js_str($s) {
   return '"'.addcslashes($s, "
<?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>
..\"\").'"'; } 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());

回答by Sander

For a multidimensionalarray in PHP4 you can use the following addition to the code posted by Udo G:

对于PHP4 中的多维数组,您可以在 Udo G 发布的代码中添加以下内容:

##代码##

回答by japetko

This is my function. JavaScript must be under PHP otherwise use SESSION.

这是我的职能。JavaScript 必须在 PHP 下,否则使用 SESSION。

##代码##

Last row can be ....text(jsArray); and will be shown "1,2,3,4,5,6"

最后一行可以是 ....text(jsArray); 并将显示“1,2,3,4,5,6”