【问题标题】:How to convert an array of items to their coressponding array of id如何将项目数组转换为其对应的 id 数组
【发布时间】:2014-10-29 08:51:46
【问题描述】:

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

id ingredient

1   egg
2   peanut
3  treenut
4   oil

现在我有一个数组作为成分=[花生,油,鸡蛋]

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

成分=[2,4,1] 谁能帮忙??

提前谢谢...

【问题讨论】:

  • 添加一些你尝试过的代码。
  • array_flip() 将使用项目切换数组键。 ca2.php.net/manual/en/function.array-flip.php
  • 原料从何而来?我假设它们无论如何都来自数据库,因此您在获得名称的地方应该能够更改它以返回 IDS
  • 查询应该类似于"SELECT id FROM table WHERE igredient in (".implode($ingredients,",").");"

标签: php mysql arrays database


【解决方案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

【讨论】:

    【解决方案2】:

    试试这个...

    $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'];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      相关资源
      最近更新 更多