2017-04-07 88 views
2

现在有很多人遇到同样的问题,他们的解决方案也没有奏效。将PHP数组转换为Javascript对象console.log后没有数组

问题

我有一个从REST调用返回的时间列表。除了我希望将它们存储到JavaScript数组中之外,它们的创建方式与它们应该完全相同。

PHP

function getOpenAppts() 
{ 
    global $wpdb; 
    $final_array = ""; 
    $td = date('m/d/Y'); 
    $datetime = new DateTime('tomorrow'); 
    $tm = $datetime->format('Y-m-d'); 
    $startDate = $td; 
    $endDate = $tm; 
    $apptTypeID = "23"; 
    $get_loc = $wpdb->get_results('SELECT provid,id FROM location'); 
    foreach($get_loc as $val){ 
    // call to Athena to get open appointments 
     $res = getOpenAppointments($val->id, $val->provid, $startDate, $endDate, $apptTypeID); 
     //print_r($res); 

     // if we got some appointments back strip any that started before now 
     if (array_key_exists('totalcount', $res) && $res['appointments'] > 0) 
     { 
      $tzStr = "America/Los_Angeles"; 
      $tzObject = new DateTimeZone($tzStr); 
      $nowDT = new DateTime(); 
      $nowDT->setTimezone($tzObject); 
      //print_r($nowDT); 
      //print_r("\n"); 
      $appts = array(); 
      for ($i = 0; $i < count($res['appointments']); $i++) 
      { 
       $apptDT = new DateTime($res['appointments'][$i]['date']." ".$res['appointments'][$i]['starttime'], $tzObject); 
       //print_r($apptDT); 
       //print_r("\n"); 
       if ($nowDT < $apptDT) 
        $appts[] = $res['appointments'][$i]; 
      } 
     } 

     if (count($appts) > 0) 
      foreach($appts as $data) { 
       $final_array[] = $data; 
     } 

     else 
      $res; // something went wrong. return error message 
    } 
    echo json_encode($final_array); 
} 

的header.php

<script> 
    var times = <?php getOpenAppts(); ?>; 
    console.log(times); //Will display properly 
</script> 

enter image description here 这正是它应该怎么回来!

但是...当我运行的变量次控制台(这是使其成为一个全局变量的头,我得到这个。 enter image description here

它应该给我确切的同一列表的控制台。日志给我

我曾尝试

我跑:

PARSE.json(times); 

没有效果...

我做在PHP:

​​

无效果......

哪一部分这个过程是不正确的?

+0

这是PHP里面的函数getOpenAppts()'? –

+2

也许你在其他地方压倒了它?尝试改变它的名字是不寻常的,并保持console.log –

+0

刚刚更新了PHP – Cam

回答

1

您在使用time作为全局变量。

由于声明后的console.log打印一切正常,您可能会在某处之后重写其值。

避免最多你可以全局变量,他们是邪恶的:)