2011-06-08 74 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); 
}