Php 如何将项目数组转换为其id的CoreSponding数组

Php 如何将项目数组转换为其id的CoreSponding数组,php,mysql,arrays,database,Php,Mysql,Arrays,Database,我的MySQL数据库中有一个表,其中包含以下成分: id ingredient 1 egg 2 peanut 3 treenut 4 oil 现在我有一个数组作为配料=[花生、油、蛋] 我必须将此数组转换为id的对应数组,如下所示: id ingredient 1 egg 2 peanut 3 treenut 4 oil 成分=[2,4,1] 有人能帮忙吗 提前感谢…试试这个 $ingridents = array("peanut", "oil", "eg")

我的MySQL数据库中有一个表,其中包含以下成分:

id ingredient

1   egg
2   peanut
3  treenut
4   oil
现在我有一个数组作为配料=[花生、油、蛋]

我必须将此数组转换为id的对应数组,如下所示:

id ingredient

1   egg
2   peanut
3  treenut
4   oil
成分=[2,4,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
$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'];
}

添加一些您尝试过的代码。
array\u flip()
将使用项目切换数组键。这些配料是从哪里来的?我假设它们都来自数据库,所以在获取名称的地方,您应该能够更改它以返回id。查询应该类似于
“从igredient所在的表中选择id(“.infrade($components,”);”