简体   繁体   English

PHP数组到JavaScript对象

[英]php array to javascript objects

hi there im having a problem adding values to my graph from php array to javascript object so far i have a php values in the array 您好,我在将值从php数组添加到javascript对象的图形中时遇到问题,到目前为止,我在数组中具有php值

$data=array(5,10,15,20);

and i converted it to json to prepare for javascript 我将其转换为json以准备javascript

$js_array = json_encode($data);

and heres the javascipt part 这是javascipt部分

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

i think it is reading it as 我认为这是作为阅读

data : [5] or data : [5101520]

it was suppose to read it as 本来想读成

data : [5,10,15,20]

thanks guys hoping you can help me 谢谢大家希望你能帮助我

here is the php array storing 这是PHP数组存储

<?php  
$data = array();

$que = "SELECT name FROM table1 ORDER BY date ASC";

$res = mysql_query($que, $con);

if(mysql_num_rows($res)>0){

while($row = mysql_fetch_array($res)){

$data[] = $row['name'];

}}

$js_array = json_encode($data);

?>'

here is the var dump data echo array(4) { [0]=> string(1) "5" 1 => string(2) "10" [2]=> string(2) "20" [3]=> string(2) "15" } 这是var dump data echo array(4){[0] => string(1)“ 5” 1 => string(2)“ 10” [2] => string(2)“ 20” [3] = > string(2)“ 15”}

这是当前的输出

php PHP

// array
$data = array(1,2,3,4,5);
// array -> json
$json = json_encode($data);
// print json
echo $json;

js with jquery: 带有jQuery的js:

$.getJSON( "script.php", function( data ) {
console.log(data)
}

The way you have defined php array will throw syntax error. 您定义php数组的方式将引发语法错误。

Use like this : 像这样使用:

<?php
$data=array(5,10,15,20);
print_r(json_encode($data));
?>

It'll give you output : 它会给你输出:

data : [5,10,15,20]

Here is the demo : http://codepad.org/UVFT6m67 这是演示: http : //codepad.org/UVFT6m67

Now you can use this json object with your javascript. 现在,您可以将此json对象与javascript一起使用。

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

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