2016-08-01 76 views
0

我正在做一個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>"; 

該代碼返回此。

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

誰能告訴我爲什麼使用字符串變量失敗,並使用字符串文字工作?

回答

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

找到