【问题标题】:String comparison failing in an anonymous function when using a string variable使用字符串变量时,匿名函数中的字符串比较失败
【发布时间】:2016-08-01 02:34:13
【问题描述】:

我正在调用 API 以获取多维数组。然后我使用 array_filter 来尝试获取具有特定结束日期的特定数组。我正在使用的代码如下:

$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>";

该代码返回 this。

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

如果我改为在匿名函数中使用字符串文字...

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

我明白了。

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"
  }
}

谁能告诉我为什么使用字符串变量失败而使用字符串字面量有效?

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    不要禁用错误报告,否则您会收到 $date_formatted 未定义的通知。

    $date_formatted 在您的匿名函数的上下文中不存在。你可以使用use从父作用域继承变量:

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

    更多信息请访问http://php.net/manual/en/functions.anonymous.php

    【讨论】:

      猜你喜欢
      • 2012-06-04
      • 1970-01-01
      • 2012-10-04
      • 2016-07-05
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多