0


我想获取标题和标题的标签。

public function titles()
{
     $query=mysql_query("SELECT * FROM title");
     while($row = mysql_fetch_object($query)){
          $data->title[] = $row;
          $data->tag[] = $this->tags($row->id);
     }
     return $data;
}

public function tags($title_id)
{
     $query=mysql_query("SELECT * FROM tag WHERE title_id = '$title_id'");
     while($row = mysql_fetch_object($query)){
           $tag[] = $row;
     }
     return $tag;
}

我正在尝试以这种方式打印

$data = titles();
foreach($data->title as $title)
{
     echo $title->topic;
     foreach($data->tag as $tag)
     {
         echo $tag->name;
     }
}

但它不起作用。我能怎么做?谢谢你的帮助。

4

1 回答 1

1

你应该在你的titles方法中有这样的东西

$data = new stdClass();
$data->title = array();
$data->tag = array();

您还需要添加这样的文件

$data->title[$row->id][] = $row;
$data->tag[$row->id][] = $this->tags($row->id);

然后你可以像这样循环

foreach($data->title as $id => $title)
{
    echo $title->topic;
    foreach($data->tag[$id] as $tag)
    {
        echo $tag->name;
    }
}

同时启用错误,以便您可以在页面顶部看到 PHP 错误 ..

error_reporting(E_ALL);
ini_set("display_errors","On");

PHP 文档开启mysql_***

不鼓励使用此扩展程序。相反,应该使用 MySQLi 或 PDO_MySQL 扩展。另请参阅 MySQL:选择 API 指南和相关的常见问题解答以获取更多信息。此功能的替代品包括

我认为你的代码应该是什么样子

class Somthing {
    private $db;

    function __construct() {
        $this->db = new mysqli("localhost", "user", "password", "db");
    }

    function titles() {
        $data = new stdClass();
        $data->title = array();
        $data->tag = array();

        $result = $this->db->query("SELECT * FROM title");
        while ( $row = $result->fetch_object() ) {
            $data->title[$row->id] = $row;
            $data->tag[$row->id] = $this->tags($row->id);
        }
        return $data;
    }

    function tags($title_id) {
        $tag = array();
        $result = $this->db->query("SELECT * FROM tag WHERE title_id = '$title_id'");
        while ( $row = $result->fetch_object() ) {
            $tag[] = $row;
        }
        return $tag;
    }
}

$somthing = new Somthing();

foreach ($somthing->titles() as $id => $title ) {
    echo $title->topic;
    foreach ( $data->tag[$id] as $tag ) {
        echo $tag->name;
    }
}
于 2012-10-12T23:39:18.690 回答