简体   繁体   English

PHP / JavaScript:如何将数组从PHP传递到JavaScript

[英]PHP / JavaScript: how to pass array from PHP to JavaScript

I use the following PHP lines to convert some simpleXML data to an array: 我使用以下PHP行将一些simpleXML数据转换为数组:

$dataRaw = array();
foreach($objCount->escalations as $esc) {
    $dataRaw[(string)$esc->region] = (int)$esc->volume;
}
$dataPrep = json_decode(json_encode($dataRaw), TRUE);

Printing this returns the following which looks ok to me: 打印此命令返回以下内容,对我来说不错:

Array ( [af] => 6 [as] => 295 [eu] => 249 [na] => 279 [oc] => 42 [sa] => 10 ) 

I then tried to pass this in a JS function using the following line but this doesn't work. 然后,我尝试使用下面的代码行在JS函数中传递它,但这不起作用。 I am not getting any errors, the chart just doesnt show at all with this, probably because it doesn't recognise the content. 我没有收到任何错误,图表根本不显示任何错误,可能是因为它无法识别内容。

data: <?php echo $dataPrep;?>

When I hard-code the "data" values in JS as follows then everything works fine so I am probably passing it wrong. 当我按照以下方式对JS中的“数据”值进行硬编码时,则一切正常,因此我可能传递了错误的信息。

var data = [{ 'hc-key': 'af', value: 6 },
    { 'hc-key': 'as', value: 295 },
    { 'hc-key': 'eu', value: 249 },
    { 'hc-key': 'na', value: 279 },
    { 'hc-key': 'oc', value: 42 },
    { 'hc-key': 'sa', value: 10 }];

Can some tell me what I have to change here ? 有人可以告诉我在这里我需要更改吗?

Many thanks in advance, Tim. 蒂姆,非常感谢。

You need to pass the encoded data, not after decoding it. 您需要传递编码的数据,而不是在解码之后。 As after decoding, it change into array and directly we can not assign array to js variable: 解码后,它变为数组,我们不能直接将数组分配给js变量:

foreach($objCount->escalations as $esc) {
    $dataRaw[(string)$esc->region] = (int)$esc->volume;
}
$dataPrep = json_encode($dataRaw);

and for js variable : 和js变量:

data: <?php echo $dataPrep;?>
data: <?php echo json_encode($dataPrep); ?>

PHP手册: json_encode() - http://www.php.net/manual/en/function.json-encode.php

Try this to get the desired structure: 尝试这样做以获得所需的结构:

foreach($objCount->escalations as $esc) {
    $dataRaw[] = array( 'hc-key' => (string) $esc->region, 'value' => (int) $esc->volume );
}

data: <?php echo json_encode( $dataRaw ); ?>

When you json_encode your data, you will have to parse it as json in javascript before you have an array again. 当您对数据进行json_encode编码时,您必须在javascript中将其解析为json,然后才能再次获得数组。 Use for example: http://api.jquery.com/jquery.parsejson/ 例如使用: http : //api.jquery.com/jquery.parsejson/

But in your case, you have already converted it back to a php array by calling json_decode. 但就您而言,您已经通过调用json_decode将其转换回php数组。 You cannot echo a php-array and expect it to show in the source like a javascript array. 您不能回显php-array并期望它像javascript数组一样在源中显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM