我尝试使用定制的usort功能。当我加载5个单元阵列时,这个运行超过30秒,然后发出致命错误。
我试图找出我是否已经成为一个无限循环但是没有创建它。
数组:
Array ( [0] => Array ( [Name] => iPhone 5s 32 GB [Price] => 0 [Description] => A new Apple Product [Image_URL] => [Business_ID] => 6 [Keywords] => ["iPhone","iPhone 5s","Apple","32 GB"] ) [1] => Array ( [Name] => iPhone 4s 32 G [Price] => 300 [Description] => Apple iPhone 4S [Image_URL] => [Business_ID] => 6 [Keywords] => ["iPhone 4S","iPhone","Apple","32 GB"] ) )
搜索:
$searchTerm = "iphone 5s";
代码:
if (!empty($searchTerm)) {
$searchTermWords = explode(" ", $searchTerm);
usort($products, function($a, $b) use ($searchTermWords) {
$aArr = explode(" ", $a['Name']);
$bArr = explode(" ", $b['Name']);
$aKeywords = $a['Keywords'];
$bKeywords = $b['Keywords'];
//todo: explode description too.
$aCount = 0;
$bCount = 0;
for ($i = 0; $i < $searchTermWords; $i++) {
for ($j = 0; $j < $aKeywords; $j++) {
if (strpos($aKeywords[$j], $searchTermWords[$i]) !== false)
$aCount++;
}
for ($j = 0; $j < $aArr; $j++) {
if ($aArr[$j] == $searchTermWords[$i])
$aCount++;
}
for ($j = 0; $j < $bKeywords; $j++) {
if (strpos($bKeywords[$j], $searchTermWords[$i]) !== false)
$bCount++;
}
for ($j = 0; $j < $bArr; $j++) {
if ($bArr[$j] == $searchTermWords[$i])
$bCount++;
}
}
return $bCount - $aCount;
});
}
错误(30秒后):
Fatal error: Maximum execution time of 30 seconds exceeded in /home/itay/public_html/tester.php(30) : eval()'d code on line 94
如果由于某种原因而导致一切都是由eval()函数构成的。
答案 0 :(得分:0)
您收到致命错误,因为您的脚本无法正常退出。有一个无限运行的For循环。
根据元素本身检查for()
循环,而不是元素数。您是否尝试循环数组中的元素数量?如果是这样,请尝试使用count($array)
返回数组中的元素数。然后使用该计数循环使用foreach。