dougou8458 2016-08-01 02:34
浏览 44
已采纳

使用字符串变量时,匿名函数中的字符串比较失败

I'm making an API call to get a multidimensional array. I'm then using array_filter to try to get the specific array that has a specific end date. The code I'm using is below:

$api_call = "287/terms";

$terms_json = curl_exec(makeAPIConnection($api_call));
$all_terms = json_decode($terms_json);

if(!is_array($all_terms)) { return NULL; }

// Getting current date and formatting for comparison
$current_date = date_create('2017-05-25');
$date_formatted = date_format($current_date, 'Y-m-d');

// Getting the current term
$current_term = array_filter($all_terms, function($a) {
    if(substr($a->EndDate, 0, 10) === $date_formatted) {
        return true;
    }
    return false;
});

echo "<pre>";
var_dump($date_formatted) . "<br";
var_dump($current_term) . "<br";
echo "</pre>";

That code returns this.

string(10) "2017-05-25"
array(0) {
}

If I instead use a string literal in the anonymous function...

$current_term = array_filter($all_terms, function($a) {
    if(substr($a->EndDate, 0, 10) === '2017-05-25') {
        return true;
    }
    return false;
});

I get this.

string(10) "2017-05-25"
array(1) {
  [3]=>
  object(stdClass)#4 (7) {
    ["AcadSessionId"]=>
    int(287)
    ["Code"]=>
    string(4) "Qtr4"
    ["Description"]=>
    string(20) "Quarter 4/Semester 2"
    ["EndDate"]=>
    string(19) "2017-05-25T00:00:00"
    ["Id"]=>
    int(729)
    ["Name"]=>
    string(20) "Quarter 4/Semester 2"
    ["StartDate"]=>
    string(19) "2017-03-13T00:00:00"
  }
}

Can anyone tell me why using the string variable is failing and using the string literal is working?

  • 写回答

1条回答 默认 最新

  • dsutuyxe088689 2016-08-01 02:42
    关注

    Don't disable error reporting or else you would have gotten a notice that $date_formatted was undefined.

    $date_formatted does not exist in the context of your anonymous function. You can inherit variables from the parent scope by using use:

    $current_term = array_filter($all_terms, function($a) use ($date_formatted) {
        if(substr($a->EndDate, 0, 10) === $date_formatted) {
            return true;
        }
        return false;
    });
    

    More information can be found at http://php.net/manual/en/functions.anonymous.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题