我无法访问数组php的特定索引

时间:2019-06-30 19:54:37

标签: php mysql sql arrays string

我无法访问数组的特定索引,我想访问实际上包含用户邮政编码的数组的第三个索引,以便在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;
    }

}

1 个答案:

答案 0 :(得分:2)

fetchAll返回数组数组。因此,如果您print_r(zip_code);,您将看到类似的内容:

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

因此,如您所见-此处没有索引为2的键,外部数组中只有0,子数组中有两个键0zipcode

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

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