0

信息

这应该是一个相当简单的问题。在我的网站上,我的数据库中有一个 post_categorys,其结构如下

    ID    |    Name
    1     |   Sports
    2     |   Health
    3     |   Movies
    4     |   Music

现在,当我保存博客文章时,我会在 blog_post 表中保存 category_id,例如1for 。movies

将博客文章打印给我的用户时,我希望能够通过类似的方式获取博客文章类别名称$categorys[$blog_cat_id']['name']

这是我如何获得$categorys上面使用的所有类别的方法。

function getCategorysArray(){
    $STH = $this->database->prepare('SELECT * FROM project_categorys');
    $STH->execute();
    return $STH->fetchAll();
}

但这会以这种格式返回数组

Array
(
[0] => Array
    (
        [id] => 1
        [0] => 1
        [name] => Sports
        [1] => Sports
    )

[1] => Array
    (
        [id] => 2
        [0] => 2
        [name] => Health
        [1] => Health
    )

[2] => Array
    (
        [id] => 3
        [0] => 3
        [name] => Movies
        [1] => Movies
    )

[3] => Array
    (
        [id] => 4
        [0] => 4
        [name] => Music
        [1] => Music
    )

因此我无法使用我想要的方法来获取类别名称($categorys[$blog_cat_id']['name']

问题

有没有办法我可以以某种方式重新映射数组以便$array[1]['name']=Sports成为输出?

4

3 回答 3

2

尝试这个:

function getCategorysArray(){
    $STH = $this->database->prepare('SELECT * FROM project_categorys');
    $STH->execute();
    $res = $STH->fetchAll(PDO::FETCH_ASSOC);
    $categories = array();
    foreach($res as $row){
        $categories[$row['id']] = $row;
    }
    return $categories;
}
于 2013-11-06T13:59:43.627 回答
1
public function getCategories()
{
  if (null == $this->categories) {
    $stmt = $this->database->preapre('SELECT id, name FROM project_categorys')->execute();
    $categories = $stmt->fetchAll();

    foreach($categories as $category) {
      $this->categories[$category['id']] = $category;
    }
  }
  return $this->categories;
}
于 2013-11-06T14:00:03.407 回答
1

所以,基本上,您希望数组由id?

首先,您可以通过调用来简化数组fetchAll(PDO::FETCH_ASSOC)。这意味着您将不再在返回的数组中有那些不必要的01索引。

那么最简单的解决方案就是简单地遍历返回的数组。

$STH = $this->database->prepare('SELECT * FROM project_categorys');
$STH->execute();
$results = $STH->fetchAll(PDO::FETCH_ASSOC);
$ret = array();
foreach ($results as $row) {
    $ret[$row['id']] = $row['name'];
}
return $ret;

也许更好的是,我们可以删除fetchAll调用,因为PDOStatementTraversable

$STH = $this->database->prepare('SELECT * FROM project_categorys');
$STH->execute();

$ret = array();
foreach ($STH as $row) {
    $ret[$row['id']] = $row['name'];
}
return $ret;
于 2013-11-06T14:00:26.213 回答