php - 从查询数组中获取第一个元素

标签 php mysql parameter-passing

  $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));

current() Reference

关于php - 从查询数组中获取第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14987084/

相关文章:

php - 选择所有值并对不同表中的字段值同时求和

php - woocommerce PayPal 链接错误 - 逗号而不是点

PHP xls、xlsx、ppt、pptx 标题

MySql select IN 子句字符串逗号分隔

php - 如何在 html 表中填充 UNION ALL 查询数据

python - 我可以将对象传递给 argparse.add_argument 吗?

nhibernate - 当参数之一是列表时,如何将参数传递给 NHibernate 中的存储过程?

parameter-passing - 在 liquibase 中使用配置文件

PHP编码约定?

php - latin1 到 utf8 转换问题