使用PHP是将索引字符串从数据库转换为其名称值的最有效方法


Using PHP what is the most efficent way to convert a string of index's to thier name value from a database?

假设我已经建立了与数据库的连接并且一切正常。如何有效地迭代像这样的字符串 $item ["tags"]=> string(54) "1,2,3,4,5,6,7,9,10,11,12,13,14,17,18,19,20,21,25,28,31"

并将这些索引值替换为存储在"标签"数据库表中的名称,例如...

id ...名字
1 ..........关系
2 ..........服务业
3 ..........咨询

使用 php 和 mysqli...提前谢谢。

您可以使用以下内容:

$mysqli = new mysqli("host", "user", "password", "database");
$sql = sprintf("SELECT id, Name FROM table_name WHERE id IN (%s)", $mysqli->escape_string($item['tags']));

如果使用 $sql 作为查询字符串,则查询结果将是一个行数组,其中 id 与其Name匹配。如果您希望它具有类似 $array[<id>] = <name> 的结构,请考虑执行以下操作:

$result = $mysqli->query($sql);
if($result->num_rows > 0) {
    $returnArray = array();
    while($row = $result->fetch_array(MYSQLI_ASSOC)) {
        $returnArray[$row['id']] = $row['Name'];
    }
}

这将做的是查询您的MySQL服务器,检查SQL查询是否返回了任何结果,如果返回了,它将在具有id -> Name结构的数组中解析所有结果。

我去了:

                    if ( $item->tags ) {
        $eachTag = explode(",", $item->tags);
            foreach ($eachTag as $key => $value) {
                $result = mysql_query("SELECT `name`,`id` from tags WHERE `id`=$value");
                $row = mysql_fetch_array($result);
                if ($row != "") {
                    $tagsWithName .= $row['name'].", ";
                }   
            }
        $tagsWithName = rtrim($tagsWithName, ", ");

不过可能还有更好的...