dqwd71332
2015-02-03 01:15
浏览 11
已采纳

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

Assuming I have established a connection to the database and all is well. How can I iterate efficiently through a string like $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"

and replace these index values with the name stored in a "tags" database table like ...

id ......... Name
1 .......... Relationships
2 .......... Services
3 .......... Counseling

Using php and mysqli... Thanks in advance.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dpxnrx11199 2015-02-03 01:53
    已采纳

    I went with :

                        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, ", ");
    

    There is probably better though ...

    已采纳该答案
    打赏 评论
  • douzhangbao2187 2015-02-03 01:27

    You could use the following:

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

    If you use $sql as the query string, the query result will be a array of rows with ids matching their Name. If you want it to have a structure like $array[<id>] = <name>, consider doing the following:

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

    What this will do, is query your MySQL server, check if the SQL query returned any result and if it did it'll parse the result all in an array where you have a id -> Name structure.

    打赏 评论

相关推荐 更多相似问题