我正在开发一个小项目,我需要从每行返回一组值,但只能从表中的一列(页面)返回。
我的方法如下:
public static function getMainArray() {
$conn = parent::connect();
$sql = "SELECT page FROM " . TBL_PAGES . " WHERE level = 0";
try {
$st = $conn->prepare( $sql );
$st->execute();
$pages = array();
foreach ( $st->fetchAll() as $row ) {
$pages[] = new Page( $row );
}
parent::disconnect( $conn );
return array( $pages);
} catch ( PDOException $e ) {
parent::disconnect( $conn );
die( "Query failed: " . $e->getMessage() );
}
}
当我打印这个数组时,
$pages = array();
$pages = Page::getMainArray();
print_r($pages);
输出如下:
Array (
[0] => Array (
[0] => Page Object ( [data:protected] => Array (
[id] =>
[page] => home
[url] =>
[level] =>
[parent] =>
[nazov] =>
[title_navi] =>
[title_meta] =>
)
)
[1] => Page Object ( [data:protected] => Array (
[id] =>
[page] => about
[url] =>
[level] =>
[parent] =>
.
.
.
我需要更改什么才能输出如下:
Array (
[0] => home
[1] => about
[2] => orders
[3] => info
[4] => contact
)
答案 0 :(得分:0)
它必须是什么,没有所有无用的代码
public static function getMainArray() {
$conn = parent::getConnection();
$sql = "SELECT page FROM " . TBL_PAGES . " WHERE level = 0";
$st = $conn->prepare( $sql );
$st->execute();
return $st->fetchAll(PDO::FETCH_COLUMN, 0);
}
请注意parent::getConnection()
方法每次调用时都不应连接,但始终返回已打开的连接。此处不应使用parent::disconnect()
。以及try..catch。
答案 1 :(得分:-1)
更改
$pages[] = new Page( $row );
到
$pages[] = $row['page'];