爆炸使用两个foreach循环不工作

时间:2017-02-23 07:51:52

标签: php mysql

我正在尝试显示,表格中mysql分隔的数字。

我的代码是,

$result = $check->result_array();

foreach($result as $res):
    $order_id = explode(",", $res["order_id"]); // $res["order_id"] = "1,2,"

    foreach($order_id as $ord_id):
        echo $ord_id; // output: 1
        $query = $this->db->query('SELECT * FROM tbl_order o INNER JOIN tbl_contacts c ON c.contacts_id = o.contacts_id LEFT JOIN tbl_title t ON t.title_id = c.title_id LEFT JOIN tbl_assign a ON a.order_id = o.order_id LEFT JOIN (SELECT u.assign_id,max(u.status_id) as maxid FROM tbl_unit_status u group by u.assign_id) uu ON uu.assign_id = a.assign_id LEFT JOIN tbl_unit_status u2 on u2.status_id = uu.maxid LEFT JOIN tbl_cutter cu ON cu.cutter_id = u2.cutter_id LEFT JOIN tbl_worker w ON w.worker_id = u2.worker_id WHERE a.central_status = 1 AND a.central_assign_unit = 2 AND o.order_id != "'.$ord_id.'"  ORDER BY a.assign_id DESC');
        $count = $query->num_rows();

        if($count > 0) {
            return $query->result_array();
        }
        else {
            return 0;
        }
    endforeach;
endforeach;

对于上面的代码,输出为1。但我希望输出为12。我的编码有什么问题。如何解决这个问题呢。谢谢。

我已经编辑了我的代码。以上是我的实际代码。在第二个foreach循环中使用sql查询时,输出为1

1 个答案:

答案 0 :(得分:1)

合并订单

目前,您在for循环中使用了return。这意味着它会在它到达该行时立即退出,并且不再循环。因此,您将返回的值添加到数组中,然后返回

$result = $check->result_array();

// This will be the returned value:
$orders = array();

foreach($result as $res) {
    $order_id = explode(",", $res["order_id"]); // $res["order_id"] = "1,2,"

    foreach($order_id as $ord_id) {

        // If your order_id string can end in ',' then watch out for empty ID's:
        if ($ord_id == '') {
            continue;
        }

        echo $ord_id; // output: 1
        $query = $this->db->query('SELECT * FROM tbl_order o INNER JOIN tbl_contacts c ON c.contacts_id = o.contacts_id LEFT JOIN tbl_title t ON t.title_id = c.title_id LEFT JOIN tbl_assign a ON a.order_id = o.order_id LEFT JOIN (SELECT u.assign_id,max(u.status_id) as maxid FROM tbl_unit_status u group by u.assign_id) uu ON uu.assign_id = a.assign_id LEFT JOIN tbl_unit_status u2 on u2.status_id = uu.maxid LEFT JOIN tbl_cutter cu ON cu.cutter_id = u2.cutter_id LEFT JOIN tbl_worker w ON w.worker_id = u2.worker_id WHERE a.central_status = 1 AND a.central_assign_unit = 2 AND o.order_id != "'.$ord_id.'"  ORDER BY a.assign_id DESC');
        $count = $query->num_rows();

        if ($count > 0) {
            // We've got some results - merge into orders array:
            $orders = array_merge($orders, $query->result_array());
        }

    } // Removed endforeach; syntax (it's not very common)
}

// We can now return that orders set:
return $orders;

请注意,我没有对查询本身进行任何更改;一般而言,出于性能原因,上述情况要好得多a stored procedure或使用in(...) syntax代替。这样,您只运行一个查询,并且PHP与您的数据库服务器之间的来回更少。