javascript - PHP 数组到 Javascript 对象在 console.log 之后没有数组

标签 javascript php arrays json

现在有很多人遇到同样的问题,但他们的解决方案没有奏效。

问题

我有一个从 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>

enter image description here 这正是它应该返回的方式!

但是.. 当我在变量 times 上运行一个控制台时(它在标题中使其成为一个全局变量。我明白了。 enter image description here

它应该给我与 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/

相关文章:

javascript - 如何在代码更改时重新加载 html 页面

javascript - 使用 GWT/Java/JavaScript 滚动到可滚动对象的特定位置

Java解密错误: data not block size aligned

javascript - 按字符串值的长度过滤对象数组

javascript - UIWebView 调用带有参数的 JS 将不起作用

php - 在涉及 PDO 事务的嵌套原子操作方面需要帮助

php - Laravel:在 Controller 中同时使用两个请求

javascript - 数组中数字范围的总和(回调函数)

PHP array_unique 没有索引

javascript - 浏览器忽略 Javascript 文件