[英]convert php associative array into javascript object
I'm trying to load Chinese words as keys, and their English translations as values from a database into a php array so then I can use them on the client side in JavaScript.我正在尝试将中文单词作为键加载,并将它们的英文翻译作为值从数据库加载到 php 数组中,这样我就可以在 JavaScript 的客户端使用它们。 So I load the PHP key:value pairs into the JavaScript array and try to output the results as key value pair as such:因此,我将 PHP 键值对加载到 JavaScript 数组中,并尝试将结果作为键值对输出,如下所示:
stuff : Ni, You
stuff : Ta, Him or Her
stuff : Wo, I
Chinese and English words are loaded in a relational database.中英文词加载到关系数据库中。
PHP : PHP :
$wordsArray = array();
while ($row = $sql->fetch_assoc()) {
$wordsArray[$row['chinese']] = $row['english'];
}
Javascript : Here I want the $.each to output the key as a string, and not a number index. Javascript :在这里我希望 $.each 将键作为字符串输出,而不是数字索引。 So when I tried var words = [<?php echo '"'.implode('","', $wordsArray).'"' ?>];
所以当我尝试var words = [<?php echo '"'.implode('","', $wordsArray).'"' ?>];
as an array, I got:作为一个数组,我得到:
stuff : 0, You
stuff : 1, Him or Her
stuff : 2, I
When I'm really looking for:当我真正在寻找:
stuff : Ni, You
stuff : Ta, Him or Her
stuff : Wo, I
So I changed words
to be an object so that $.each
could output key as string:所以我把words
改成一个对象,这样$.each
就可以将 key 输出为字符串:
var words = {<?php echo '"'.implode('","', $wordsArray).'"' ?>};
$.each(words, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
Which throws error: SyntaxError: Unexpected token ,
抛出错误: SyntaxError: Unexpected token ,
You can use json_encode() to make array
as an json object
like,您可以使用json_encode()将array
作为json object
例如,
var words = <?php echo json_encode($wordsArray) ?>;// don't use quotes
$.each(words, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
I looked a lot for an elegant solution to fix this issue without doing changing things over javascript or just replace quotes via preg_replace (for the case that the values would contain quotes) and end up doing it by myself.我寻找了很多优雅的解决方案来解决这个问题,而无需通过 javascript 进行更改,或者只是通过 preg_replace 替换引号(对于值将包含引号的情况)并最终由我自己完成。 even if it's too late, I hope it would help those who are looking for the same solution.即使为时已晚,我希望它会帮助那些正在寻找相同解决方案的人。
function json_encode_advanced(array $arr, $sequential_keys = false, $quotes = false, $beautiful_json = false) {
$output = "{";
$count = 0;
foreach ($arr as $key => $value) {
if ( isAssoc($arr) || (!isAssoc($arr) && $sequential_keys == true ) ) {
$output .= ($quotes ? '"' : '') . $key . ($quotes ? '"' : '') . ' : ';
}
if (is_array($value)) {
$output .= json_encode_advanced($value, $sequential_keys, $quotes, $beautiful_json);
} else if (is_bool($value)) {
$output .= ($value ? 'true' : 'false');
} else if (is_numeric($value)) {
$output .= $value;
} else {
$output .= ($quotes || $beautiful_json ? '"' : '') . $value . ($quotes || $beautiful_json ? '"' : '');
}
if (++$count < count($arr)) {
$output .= ', ';
}
}
$output .= "}";
return $output;
}
function isAssoc(array $arr) {
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
usage:用法:
$array = [
'someField' => '"value"', // double quotes for string if needed
'labelField' => '"label"', // double quotes for string if needed
'boolean' => false,
'numeric' => 5,
'render' => [
'option' => 'function() {
console.log("Hello World!");
console.log(\'Hello World!\');
}',
],
];
echo json_encode_advanced($array);
result:结果:
{
someField : "value",
labelField : "label",
boolean : false,
numeric : 5,
render : {
option : function() {
console.log("Hello World!");
console.log('Hello World!');
}
}
}
The answer of Rohan Kumar is excellent except it uses jQuery to show the results. Rohan Kumar 的答案非常好,只是它使用 jQuery 来显示结果。
This can be quicker and easier:这可以更快更容易:
var words = <?php echo json_encode( $wordsArray ) ?>;
console.dir(words);
This gives you a one line result like Object ▶
.这会给你一个像Object ▶
这样的单行结果。 Clicking on the ▶
will open the object and shows its contents.单击▶
将打开对象并显示其内容。
For me the simplest way to convert php array to javascript object is to json_encode the php array then JSON.parse it from javascript like this:对我来说,将 php 数组转换为 javascript 对象的最简单方法是对 php 数组进行 json_encode,然后像这样从 javascript JSON.parse 它:
<?php
$array = [1 => "one", 2 => "two", 3 => "three"];
?>
<script>
const jsObject = JSON.parse(`<?= json_encode($array) ?>`)
console.log(jsObject) // Object { 1: "one", 2: "two", 3: "three" }
</script>
I just changed a few things to make it more compatible (line 3 and 29):我只是更改了一些内容以使其更兼容(第 3 行和第 29 行):
function json_encode_advanced(array $arr, $sequential_keys = false, $quotes = false, $beautiful_json = false) {
$output = isAssoc($arr) ? "{" : "[";
$count = 0;
foreach ($arr as $key => $value) {
if (isAssoc($arr) || (!isAssoc($arr) && $sequential_keys == true )) {
$output .= ($quotes ? '"' : '') . $key . ($quotes ? '"' : '') . ' : ';
}
if (is_array($value)) {
$output .= json_encode_advanced($value, $sequential_keys, $quotes, $beautiful_json);
}
else if (is_bool($value)) {
$output .= ($value ? 'true' : 'false');
}
else if (is_numeric($value)) {
$output .= $value;
}
else {
$output .= ($quotes || $beautiful_json ? '"' : '') . $value . ($quotes || $beautiful_json ? '"' : '');
}
if (++$count < count($arr)) {
$output .= ', ';
}
}
$output .= isAssoc($arr) ? "}" : "]";
return $output;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.