现在有很多人遇到同样的问题,但他们的解决方案没有奏效。
问题
我有一个从 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);
}
标题.php
<script>
var times = <?php getOpenAppts(); ?>;
console.log(times); //Will display properly
</script>
但是.. 当我在变量 times 上运行一个控制台时(它在标题中使其成为一个全局变量。我明白了。
它应该给我与 console.log 给我的完全相同的列表。
我尝试过的
我跑了:
PARSE.json(times);
没有影响...
我用 PHP 做了:
json_encode(json_decode($appts),true);
没有影响...
这个过程的哪一部分是不正确的?
最佳答案
您正在使用 time
作为全局变量。
由于 console.log
在声明之后打印出一切正常,您可能在之后的某个地方覆盖了它的值。
尽可能避免全局变量,它们是邪恶的:)
关于javascript - PHP 数组到 Javascript 对象在 console.log 之后没有数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283840/