简体   繁体   中英

d3 - Uncaught TypeError: data.forEach is not a function

I am working with a scatter plot in d3. I am successfully connected to my database with the php script below but when I run my d3 code I get the error:

Uncaught TypeError: data.forEach is not a function

On the connection call to the php script in my d3 code:

d3.json("connection.php", function(error, data){
if (error) throw error;
data.forEach(function(d) {
    d['TITLE'] = d.TITLE.toString();
    d['YEAR'] = +d['YEAR'];
    d['counter'] = +d['counter'];
    console.log(data.query1Results);
    console.log(data.query2Results);
    })

Here is my php script:

<?php
$username = "xxx"; 
$password = "";   
$host = "xxxx";
$database="xxxx";

$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);

$data = array(
'query1Results' => array(),
'query2Results' => array()
);

$myquery = "SELECT  `ID`, `TITLE`, `YEAR`, `In_library` FROM  `papers` where In_library = 1";

$query1 = mysql_query($myquery);

if ( ! $query1 ) {
    echo mysql_error();
    die;
}

for ($x = 0; $x < mysql_num_rows($query1); $x++) {
    $data['query1Results'][] = mysql_fetch_assoc($query1);
}

$query2 = mysql_query("SELECT `ID_to`, count(*) as `counter` from `citations` group by `ID_to` DESC");

if ( ! $query2 ) {
    echo mysql_error();
    die;
}

for ($x = 0; $x < mysql_num_rows($query2); $x++) {
    $data['query2Results'][] = mysql_fetch_assoc($query2);
}

echo json_encode($data);     

mysql_close($server);


?>

Would be very grateful if anyone could tell me what is causing this error and possible solutions as I cant see where I have gone wrong (probably because I have been looking at is for so long!) thanks in advance.

You would have to create an empty array before the d3.json() and then put the data into the empty array like this:

 var arr=[];
   d3.json("connection.php", function(data){
       arr = data;

        arr.forEach((d)=>{
d['TITLE'] = d.TITLE.toString();
d['YEAR'] = +d['YEAR'];
d['counter'] = +d['counter'];
console.log(data.query1Results);
console.log(data.query2Results);
});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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