0

我有一个这样的 SQL 查询字符串:

SELECT * FROM `oc_product` WHERE `manufacturer_id` = ? AND `date_added` < ?  `product_id` IN (?) AND `price` > ? ORDER BY `product_id` ASC;

这将移交给 Query 类构造函数,如下所示:

$query = new Query("SELECT * FROM `oc_product` WHERE `manufacturer_id` = ? AND `date_added` < ?  `product_id` IN (?) AND `price` > ? ORDER BY `product_id` ASC;", 27, date("Y-m-d H:i:s"), [17,18,29,30,46,47], 27.75);

我目前有一个函数,它用问号作为分隔符来分解字符串,计算标记的数量并遍历参数,重新组合查询字符串,因此,对于每个作为数组的参数,我将其问号替换为许多问号作为参数都在数组中(因此,IN (?)它不会像 一样被纠正IN (?,?,?,?,?,?))。

但是,我不喜欢我的函数的外观,并希望找到一个更好的等价物,或者如果可能的话,一个正则表达式/函数/SPL 驱动的过程,以使替换比我目前所做的容易得多。

你能给我一个提示吗?

4

2 回答 2

2

尝试这样的事情;

$params = array(27, date("Y-m-d H:i:s"), '[17,18,29,30,46,47]', 27.75);
$counter = 0;

$query = "SELECT * FROM `oc_product` WHERE `manufacturer_id` = ? AND `date_added` < ?  `product_id` IN (?) AND `price` > ? ORDER BY `product_id` ASC;";

echo preg_replace_callback('/\?/', function($matches) {
    $GLOBALS['counter']++;

    return $GLOBALS['params'][$GLOBALS['counter']-1];
}, $query);

输出

SELECT * FROM `oc_product` WHERE `manufacturer_id` = 27 AND `date_added` < 2013-04-08 10:29:43 `product_id` IN ([17,18,29,30,46,47]) AND `price` > 27.75 ORDER BY `product_id` ASC;

不确定IN ([17,18,29,30,46,47])部分,但您可以根据自己的喜好在$params数组中修改字符串。

祝你好运!

于 2013-04-08T08:31:40.310 回答
0

找到了解决方案。仅用于 SQL 查询部分,但它非常快并且看起来很简单:

// takes ~1.25ms to complete (on average)
function str_replace_nth($haystack, $needle, $occurrence, $replacement) {
    $tmp = explode($needle, $haystack);

    if ($occurrence > sizeof($tmp)) {
        return $haystack;
    } else {
        $tmp[$occurrence - 1] .= "{$replacement}{$tmp[$occurrence]}";
        unset($tmp[$occurrence]);
        return implode($needle, $tmp);
    }
}
于 2013-04-08T08:21:43.747 回答