2011-06-08 51 views
2

你好,這是我使用的鱈魚,但作爲作者說它運行在PHP 5.3 我使用5.2.17我想這就是爲什麼我有這個錯誤Parse error: syntax error, unexpected T_FUNCTION上第14行(usort($entries, function ($x, $y) {修改代碼不僅在PHP 5.3中運行

我該怎麼辦?

$feeds = array(
    'http://www.example.org/feed1.rss', 
    'http://www.example.org/feed2.rss' 
); 

// Get all feed entries 
$entries = array(); 
foreach ($feeds as $feed) { 
    $xml = simplexml_load_file($feed); 
    $entries = array_merge($entries, $xml->xpath('/rss//item')); 
} 

// Sort feed entries by pubDate (ascending) 
usort($entries, function ($x, $y) { 
    return strtotime($x->pubDate) - strtotime($y->pubDate); 
}); 

print_r($entries); 

回答

4

這是因爲該代碼使用蘭巴功能。

要在前期5.3做到這一點,你可以簡單地定義函數和傳遞函數名作爲參數,即

function mySort($x, $y) { 
    return strtotime($x->pubDate) - strtotime($y->pubDate); 
} 

usort($entries, 'mySort'); 

或創建使用功能create_function()

+0

您好感謝您的回答我的作品!但是你有什麼想法爲什麼排序不起作用? – EnexoOnoma 2011-06-08 22:38:30

0

只需更換

usort($entries, function ($x, $y) { 
    return strtotime($x->pubDate) - strtotime($y->pubDate); 
}); 

通過

usort(
    $entries, 
    create_function(
     '$x, $y', 
     'return strtotime($x->pubDate) - strtotime($y->pubDate);' 
    ) 
); 
0
// Sort feed entries by pubDate (ascending) 

function mysort($x, $y) { 
    return strtotime($x->pubDate) - strtotime($y->pubDate); 
} 

usort($entries, "mysort"); 

PHP 5.3+允許使用匿名(lambda)函數。這些都是像正常功能,但不是一個名字,你會得到一個變量的引用,例如:

$myf = function() {} ; 

較早的PHP版本沒有此功能,所以你必須使用一個全球性的(正常)功能:

function myf(){ 
} 
-1

它看起來像usort()裏面的函數讓PHP感到困惑。試試這個:

// Sort feed entries by pubDate (ascending) 
function timeFix ($x, $y) { 
    return strtotime($x->pubDate) - strtotime($y->pubDate); 
}) 

$timeFix = timeFix($x, $y); 

usort($entries, $timeFix); 

或者更好的

usort($entries, timeFix($x, $y)); 

希望有所幫助。

+0

該函數是對uSort的回調函數,不應該直接調用。 – 2011-06-08 20:49:18

2

PHP 5.2.x不支持匿名函數。您仍然可以使用usort()但你需要給一個函數來進行排序:

usort($entries, "mySort"); 

function mySort($x, $y) { 
    return strtotime($x->pubDate) - strtotime($y->pubDate); 
}