2015-05-09 49 views
-4

轉換這個數組PHP/MySQL的轉換陣列WHERE子句

array("user_id"=>"8", "product_id"=>"35", "quantity"=>"1") 

查詢

select * from tbl_name where user_id='8' and product_id='35' and quantity='1' 

以及如何使用笨活動記錄功能,PHP中提供的任何方式或庫?

+3

你嘗試過什麼嗎?向我們顯示您的代碼... –

+1

如上所述,您應該顯示您的代碼,以便社區能夠指引您回到正確的方向;如果你還沒有嘗試任何代碼,下面的CodeIgniter文檔部分可能會有一些用處:https://ellislab.com/codeigniter/user-guide/database/active_record.html#select –

+0

即時通訊使用implode功能它是顯示消息'選擇*從add_to_cart在哪裏8,35,1'但我需要關聯陣列 – user3743689

回答

1

使用implodearray_map

<?php 
$where_arr = array("user_id"=>"8", "product_id"=>"35", "quantity"=>"1"); 
$where = implode(' AND ', array_map(function ($value, $key) { return "`". $key . "`='" . $value . "'"; }, $where_arr, array_keys($where_arr))); 

OR array_walk

$where_arr = array("user_id"=>"8", "product_id"=>"35", "quantity"=>"1"); 
array_walk($where_arr, function (&$value, $key) { $value = "`". $key . "`='" . $value . "'"; }); 
$where = implode(' AND ', $where_arr); 

創建查詢

$query = 'SELECT * FROM `tbl_name` WHERE '.$where; 

$query輸出:

SELECT * FROM `tbl_name` WHERE `user_id`='8' AND `product_id`='35' AND `quantity`='1' 

在你的控制,獲得數據

$where_arr = array("user_id"=>"8", "product_id"=>"35", "quantity"=>"1"); 
$results['products'] = $this->db->get_where('tbl_name', $where_arr)->result(); 

$this->load->view('your_view_name', $results); 

現在你可以在你的視圖中使用$products變量,它找到的所有產品。

0

試試這個

$array = array("user_id"=>"8","product_id"=>"35","quantity"=>"1"); 
$clauses = array(); 
foreach ($array as $field => $value) { 
    $clauses[] = "$field='$value'"; 
} 
$where_clause = join(" and ",$clauses); 
echo "select * from tbl_name where " . $where_clause;