2014-10-29 37 views
1

的陣列我有一個表,其中所含的成分如下我的MySQL數據庫:如何項的數組轉換爲自己的coressponding ID

id ingredient 

1 egg 
2 peanut 
3 treenut 
4 oil 

現在我有一個數組作爲配料= [花生,油,蛋]

我具有與本數組轉換爲相應的ID的數組如下:

成分= [2,4,1] 誰能幫助??

在此先感謝...

+1

加你嘗試過的一些代碼。 – 2014-10-29 08:53:13

+0

'array_flip()'將切換與項目的數組鍵。 http://ca2.php.net/manual/en/function.array-flip.php – 2014-10-29 08:55:11

+0

配料從何而來?我假設它們始終來自數據庫,因此,在獲取名稱的位置,您應該能夠更改它以返回IDS – 2014-10-29 08:55:48

回答

1
$ingridents = array("peanut", "oil", "eg"); 
$newArray = array(); 
$result = mysqli_query($link, "SELECT id, ingrident FROM ingridents WHERE ingrident IN (".implode(",", $ingridents).")"); 
while($row = mysqli_fetch_assoc($result) { 
    $newArray[$row['ingrident']] = $row['id']; 
} 

echo $newArray['peanut']; // would echo out the ID of peanut 
1

試試這個...

$ingredients = array("peanut", "oil", "egg"); 

$ingredients = "'".implode("','", $ingredients)."'"; 
$query = mysqli_query($link, "SELECT id, ingredient FROM table WHERE ingredient IN ($ingredients)"); 
while($row = mysqli_fetch_assoc($query) { 
    $ingredient_ids[] = $row['id']; 
} 
相關問題