2

我将其放入表列表中,它的作用是第一个函数填充前三行,然后第二个函数根据第一个函数的匹配填充第四行。

public function function1($start = 0, $max = 10, $use_result = false) {

    $sql = 'SELECT itemnum, descrip FROM TABLENAME
                WHERE itemnum LIKE "__-_____"
                AND cms_item_id IS NULL
                ORDER BY itemnum ASC
                LIMIT ' . (int)$start . ',' . (int)$max .'';
    $result = $this->registry->db->query($sql);

    $return = array();
    while($row = $result->fetch_assoc()) {
        $return[] = $row;
    }
    return $return;
}

/**
 * Get matches
 * @return array
 */
public function function2(){
    $product = $this->getList();
    foreach($product as $key) {
        $sku = $key['itemnum'];
        list(, $sku) = explode("-", $sku);
            }

    $sql = 'SELECT product_sku, long_name
    FROM TABLENAME
        WHERE product_sku = "' . $sku . '"';
    $result = $this->registry->db->query($sql);
    $return = array();

    while($row = $result->fetch_assoc()) {
        $return[] = $row;
        }
    return $return;
}

正在发生的是 3 行返回正常。但是第 4 行只返回最后一个 $sku 而不是任何匹配的东西。我知道 foreach 循环每次都被覆盖,最后一个循环被放入变量 $sku 中......但是我还能怎么做才能得到我需要的东西?

4

2 回答 2

0

制作所有 SKU 的数组,并使用IN而不是=来匹配它们。

public function function2(){
    $product = $this->getList();
    $skus = array();
    foreach($product as $key) {
        $sku = $key['itemnum'];
        list(, $sku) = explode("-", $sku);
        $skus[] = $sku;
    }
    $sku_string = implode(', ', array_map(function($x) {return "'$x'"; }, $skus));
    $sql = 'SELECT product_sku, long_name
            FROM TABLENAME
            WHERE product_sku IN (". $sku_string .")';
    $result = $this->registry->db->query($sql);
    $return = array();

    while($row = $result->fetch_assoc()) {
        $return[] = $row;
    }
    return $return;
}

也许更好的解决方案是将您的查询合并为一个:

SELECT itemnum, descrip, long_name
FROM table1 t1
JOIN table2 t2 ON t2.product_sku = substring_index(itemnum, '-', -1)
WHERE itemnum LIKE "__-_____"
AND cms_item_id IS NULL
ORDER BY itemnum ASC
LIMIT ' . (int)$start . ',' . (int)$max
于 2013-04-10T19:52:52.857 回答
0

尝试这个:

public function function2(){
    $product = $this->getList();

    $sku = array();               //Make an empty $sku array
    foreach($product as &$key) {
        $sku = $key['itemnum'];
        list(, $sku) = explode("-", $sku);
        $key['sku'] = $sku;
        $skus[] = $sku;
    }
    $selectValues = implode(',', $skus);

    $sql = "SELECT product_sku, long_name FROM TABLENAME WHERE product_sku IN($selectValues)";
    $result = $this->registry->db->query($sql);
    $return = array();

    $long_names = array();
    while($row = $result->fetch_assoc()) {
        $long_names[$row['product_sku']] = $row['long_name'];
    }

    foreach ($product as &$key) {
        $key['long_name'] = $long_names[$key['sku']];
    }
    return $product;
}
于 2013-04-10T20:08:28.260 回答