函数foreach只返回最后一个数组

时间:2013-04-10 19:39:54

标签: php function foreach

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

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 ...但是我怎么能这样做才能得到我需要的东西呢?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;
}