如何使用foreach循环在数组中存储值...?

时间:2015-04-02 09:36:16

标签: php sql arrays

我在Opencart下工作。我的大问题是应该在数组中存储值以显示结果。我的问题是>>我想在特定位置下的Db中获取产品。例如,如果班加罗尔的位置,班加罗尔的产品一个人来。

查询如下所示:

public function getvendorsbycity($city,$products)

{
    $selected_vendor = $this->db->query("SELECT * FROM " . DB_PREFIX . "vendors where city='".$city."'");

    if(isset($selected_vendor->rows) && !empty($selected_vendor->rows))
    {
        $i=0;
        foreach($selected_vendor->rows as $val)
        {

            $selected_array=array();
            if(isset($products) && !empty($products))
            {

                foreach($products as $p_val)
                {


                    $selected_products = $this->db->query("SELECT * FROM " . DB_PREFIX . "vendor v LEFT JOIN " . DB_PREFIX . "product_description pd ON v.vproduct_id=pd.product_id WHERE vendor='".$val['vendor_id']."' AND pd.name LIKE '%".$p_val['name']."%'");

                    if(isset($selected_products->rows) && !empty($selected_products->rows))
                    {
                        $selected_array[]=$selected_products->rows;
                    //I am getting result here..!

                    }
                }
            }

            $i++;
        }
    }

    //I could't get result here.! I should return the array here.
    return $selected_array;
}

任何人都可以帮助我..!提前谢谢。

2 个答案:

答案 0 :(得分:0)

请更改

$selected_array[]=$selected_products->rows;  
//I am getting result here..!

$selected_array[$i][]=$selected_products->rows;

并试试你得到的东西

答案 1 :(得分:0)

public function getvendorsbycity($city,$products)
{
    $selected_vendor = $this->db->query("SELECT * FROM " . DB_PREFIX . "vendors where city='".$city."'");
    $selected_array=array(); // we should create array here. so that we can return the result at end.
    if(isset($selected_vendor->rows) && !empty($selected_vendor->rows))
    {
        $i=0;
       //$selected_array=array(); -> its my mistake.(I wrongly created array over here.)
        foreach($selected_vendor->rows as $val)
        {


            if(isset($products) && !empty($products))
            {

                foreach($products as $p_val)
                {


                    $selected_products = $this->db->query("SELECT * FROM " . DB_PREFIX . "vendor v LEFT JOIN " . DB_PREFIX . "product_description pd ON v.vproduct_id=pd.product_id WHERE vendor='".$val['vendor_id']."' AND pd.name LIKE '%".$p_val['name']."%'");


                    if(isset($selected_products->rows) && !empty($selected_products->rows))
                    {
                        $selected_array[]=$selected_products->rows;
                    }
                }
            }

            $i++;
        }
    }

    return $selected_array;
}

}