職場のクライアントのために、Web サイトを構築しました。Web サイトには、同じタイプ/ビルドのバリアントを含めることができる提供ページがあるため、二重のクリーン URL で問題が発生しました。
ちょうど今、URLに数字を追加することでそれが起こらないようにする関数を書きました。そのクリーンな URL も存在する場合はカウントアップします。
例えば
domain.nl/product/machine
domain.nl/product/machine-1
domain.nl/product/machine-2
更新しました!$clean_url を返します。再帰時と戻り時
私が書いた関数は正常に動作しますが、正しいアプローチをとったかどうか、改善できるかどうか疑問に思っていました。コードは次のとおりです。
public function prevent_double_cleanurl($cleanurl)
{
// makes sure it doesnt check against itself
if($this->ID!=NULL) $and = " AND product_ID <> ".$this->ID;
$sql = "SELECT product_ID, titel_url FROM " . $this->_table . " WHERE titel_url='".$cleanurl."' " . $and. " LIMIT 1";
$result = $this->query($sql);
// if a matching url is found
if(!empty($result))
{
$url_parts = explode("-", $result[0]['titel_url']);
$last_part = end($url_parts);
// maximum of 2 digits
if((int)$last_part && strlen($last_part)<3)
{
// if a 1 or 2 digit number is found - add to it
array_pop($url_parts);
$cleanurl = implode("-", $url_parts);
(int)$last_part++;
}
else
{
// add a suffix starting at 1
$last_part='1';
}
// recursive check
$cleanurl = $this->prevent_double_cleanurl($cleanurl.'-'.$last_part);
}
return $cleanurl;
}