<?php
// decide if 1 or 2 is better
function selectBestImage($image1, $image2) {
// fix for strange array_filter behaviour
if ($image1 === 0)
return $image2;
list($path1, $info1) = $image1;
list($path2, $info2) = $image2;
$width1 = $info1[0];
$width2 = $info2[0];
// ugly if-block :(
if ($width1 == 260) {
return $image1;
} elseif ($width2 == 260) {
return $image2;
} elseif ($width1 == 265) {
return $image1;
} elseif ($width2 == 265) {
return $image2;
} elseif ($width1 == 600) {
return $image1;
} elseif ($width2 == 600) {
return $image2;
} elseif ($width1 == 220) {
return $image1;
} elseif ($width2 == 220) {
return $image2;
} else {
// nothing applied, so both are suboptimal
// just return one of them
return $image1;
}
}
function getBestImage($images) {
// step 1: is the absolutley best solution present?
foreach ($images as $key => $image) {
if (strpos($image, '-large') !== false) {
// yes! take it and ignore the rest.
return $image;
}
}
// step 2: no best solution
// prepare image widths so we don't have to get them more than once
foreach ($images as $key => $image) {
$images[$key] = array($image, getImageInfo($image));
}
// step 3: filter based on width
$bestImage = array_reduce($images, 'selectBestImage');
// the [0] index is because we have an array of 2-index arrays - ($path, $info)
return $bestImage[0];
}
$images = array('image1.png', 'image-large.png', 'image-foo.png', ...);
$bestImage = getBestImage($images);
?>
这应该可以工作(我没有测试过),但它不是最理想的。
它是如何工作的?首先,我们寻找绝对最好的结果,在这种情况下,-large,因为寻找子字符串是便宜的(相比之下)。
如果我们没有找到-large 图像,我们必须分析图像宽度(更昂贵!- 所以我们预先计算它们)。
array_reduce 调用一个过滤函数,该函数接受 2 个数组值并将这两个替换为函数返回的一个(更好的一个)。重复此操作,直到数组中只剩下一个值。
这个解决方案仍然不是最理想的,因为比较(即使它们很便宜)不止一次进行。我的 big-O() 符号技巧有点生疏(哈!),但我认为它是 O(n*logn)。 soulmerges 解决方案是更好的解决方案 - O(n) :)
你仍然可以改进 soulmerges 解决方案,因为不需要第二个循环:
首先,将它打包到一个函数中,这样您就可以将 return 作为中断替换。如果第一个 strstr 匹配,则返回该值并忽略其余部分。之后,您不必为每个数组键存储分数。只需比较最高的Key 变量,如果新值更高,则存储它。
<?php
function getBestImage($images) {
$highestScore = 0;
$highestPath = '';
foreach ($images as $image) {
if (strpos($image, '-large') !== false) {
return $image;
} else {
list($width) = getImageInfo($image);
if ($width == 260 && $highestScore < 5) {
$highestScore = 5;
$highestPath = $image;
} elseif ($width == 265 && $highestScore < 4) {
$highestScore = 4;
$highestPath = $image;
} elseif ($width == 600 && $highestScore < 3) {
$highestScore = 3;
$highestPath = $image;
} elseif ($width == 220 && $highestScore < 2) {
$highestScore = 2;
$highestPath = $image;
} elseif ($highestScore < 1) {
// the loser case
$highestScore = 1;
$highestPath = $image;
}
}
}
return $highestPath;
}
$bestImage = getBestImage($images);
?>
没有测试,应该在 O(n) 中工作。无法想象一种更快、更有效的方式 atm。