【问题标题】:I can't access specific indexes of my array php我无法访问我的数组 php 的特定索引
【发布时间】:2019-11-11 15:14:50
【问题描述】:

我无法访问数组的特定索引,我想访问数组的第三个索引,该索引实际上包含用户的邮政编码,以便在 SELECT 语句中使用它。这是数组:

$zip_code = connecting::query('SELECT zipcode FROM accounts WHERE username=:user_name', array(':user_name' => $user_name));
$zipcode = json_encode($zip_code, true);

这是我打印$zipcode时的输出:

[{"zipcode":"28262","0":"28262"}]

但是当我打印 $zipcode[2] 时,什么都没有打印,我不能使用它。我不能像那样直接访问它吗?我使用过 json_encode、var_export、implode 等来尝试将其转换为字符串,但它不起作用。

这是我调用的查询方法:

public static function query($query,$params = array())
{


    $statement = self :: db()->prepare($query);
    $statement->execute($params);
    if(explode(' ',$query)[0] == 'SELECT')
    {
        $data = $statement->fetchAll();
        return $data;
    }

}

【问题讨论】:

  • 为什么要将数据编码为 json?

标签: php mysql sql arrays string


【解决方案1】:

fetchAll 返回数组数组。所以,如果你print_r(zip_code); 你会看到类似的东西:

Array ( 
    [0] => Array ( 
        [zipcode] => 28262 
        [0] => 28262 
    ) 
)

所以,如您所见 - 这里没有索引为 2 的键,只有外部数组中的 0 和子数组中的两个键 0zipcode

此外,您可以看到您的数据 (28262) 在子数组中的不同键下重复。为避免这种情况,您可以向fetchAll 提供参数:

$data = $statement->fetchAll(PDO::FETCH_ASSOC);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-07
    • 2021-03-29
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多