使用 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"
并将这些索引值替换为存储在 "tags" 数据库 table 中的名称,例如 ...
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, ", ");
虽然可能更好...
假设我已经建立了到数据库的连接并且一切正常。我怎样才能有效地遍历像这样的字符串
$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"
并将这些索引值替换为存储在 "tags" 数据库 table 中的名称,例如 ...
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, ", ");
虽然可能更好...