PDO将数组返回到更易于访问的数组中

时间:2013-11-06 13:52:51

标签: php arrays multidimensional-array pdo

信息

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

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

现在,当我保存博客文章时,我在blog_post表中为1保存了{_ 1}}这样的category_id。

在向我的用户打印博客文章时,我希望能够通过类似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']作为输出?

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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;
}

答案 2 :(得分: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;