信息
这应该是一个相当简单的问题。在我的网站上,我的数据库中有一个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']
作为输出?
答案 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)
来简化数组。这意味着您将不再在返回的数组中包含那些不必要的0
和1
索引。
然后最简单的解决方案就是遍历返回的数组。
$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
来电,因为PDOStatement
是Traversable
:
$STH = $this->database->prepare('SELECT * FROM project_categorys');
$STH->execute();
$ret = array();
foreach ($STH as $row) {
$ret[$row['id']] = $row['name'];
}
return $ret;