你如何将一个 PHP 数组分配给 jQuery 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15461417/
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-25 09:16:35  来源:igfitidea点击:

How do you assign a PHP array to jQuery array?

phpjavascriptjqueryarrays

提问by user1448031

I am unable to figure out how to assign PHParray to jQueryarray?.

我无法弄清楚如何将PHP数组分配给jQuery数组?。

I want to do something like the following:

我想做如下事情:

var jQueryArray = <?php $phpArray; ?>;

Can anyone tell me how I can do this?

谁能告诉我如何做到这一点?

回答by dsgriffin

Use json encode.

使用json 编码

json_encode — Returns the JSON representation of a value

json_encode — 返回值的 JSON 表示

Example:

例子:

var arrayFromPHP = <?php echo json_encode($arr); ?>;

回答by sdespont

You need to use json_encode

你需要使用json_encode

var jQueryArray = <?php echo json_encode($phpArray); ?>;

回答by Darin Dimitrov

You could use the json_encodefunction:

您可以使用该json_encode功能:

var jQueryArray = <?php echo json_encode($phpArray); ?>;

回答by SteveP

You can use json_encode

您可以使用 json_encode

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

回答by Radiotrib

Don't forget that PHP json_encode will only work on UTF8 encoded text ...

不要忘记 PHP json_encode 只适用于 UTF8 编码的文本......

$jsonString = json_encode(array_map(utf8_encode, $rawArray));

would be a more universal solution I think, but I'm a bit tired so 'scuse any coding gaffs ...

我认为将是一个更通用的解决方案,但我有点累,所以'scuse任何编码问题......

回答by kevin

It's not going to be a JQuery array, it's a javascript array (just to clarify since it's sounds like you're probably a noob). Set your JS array to this:

它不会是一个 JQuery 数组,它是一个 javascript 数组(只是为了澄清,因为听起来你可能是个菜鸟)。将您的 JS 数组设置为:

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

See php json_encode docs: http://php.net/manual/en/function.json-encode.php

请参阅 php json_encode 文档:http: //php.net/manual/en/function.json-encode.php

回答by Thomas

You can use Json or use foreach in HTML file

您可以在 HTML 文件中使用 Json 或使用 foreach

<?php foreach($phpArray as $key => $val): ?>
      jQueryArray[<?php echo $key; ?>] = <?php echo $val; ?>
<?php endforeach; ?>