$post= ('SELECT * FROM posts WHERE id = :id LIMIT 1 ', array('id' => $_GET['id']),$conn);
$view_path = 'views/single.view.php';
require'views/layout.php';
我知道 $post 变量是一个数组,如果我在 single.view.php?id=1 上打印它
我可以得到下面的结果。
Array
(
[0] => Array
(
[id] => 1
[0] => 1
[title] => title of
[1] => first post
[body] => body of first post
[2] => body of first post
)
)
如果我写的话在 single.view.php 上
echo $post**[0]**['title'];
我可以获得标题。
但是,当我通过编写
在 single.php 上尝试此操作时$post= ('SELECT * FROM posts WHERE id = :id LIMIT 1 ', array('id' => $_GET['id']),$conn)**[0]**;
我明白
Parse error: parse error in /Library/WebServer/www/single.php on line 10
这对我来说听起来像这不是一个你无法获取它的第一个元素的数组。。
所以我的问题是如何获取 $post 变量的第一个元素。而不是将值发送到 single.view.php
最佳答案
在 PHP 5.4 之前,您无法直接从函数中检索数组元素:
$val = myArray($params)[0]; // wrong
但是,您可以这样做:
$arr = myArray($params);
$val = $arr[0];
或
$val = current(myArray($params));
关于php - 从查询数组中获取第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14987084/