简体   繁体   English

需要帮助以了解PDO的结果集

[英]Need help to understand result set from PDO

I have the following function executing PDO queries: 我有以下执行PDO查询的功能:

  // removed error handling for presenting here
  function getRows($sql) {
      $stmt = $this->db->query($sql);
      $result = $stmt->fetchAll(PDO::FETCH_ASSOC);          
      return $result;            
    } 
  }

The result is: 结果是:

Array
(
    [0] => Array
        (
            [id] => 1
            [category] => Audi
        )

    [1] => Array
        (
            [id] => 2
            [category] => BMW
        )

    [2] => Array
        (
            [id] => 3
            [category] => Chrysler
        )

)

The the following foreach code: 以下foreach代码:

foreach($result as $key => $value ) {
  echo $value.'<br/>';
}

outputs this: 输出此:

Array
Array
Array

What can I do so it returns the following? 我该怎么办,它返回以下内容?

Audi
BMW
Chrysler

I understand that I could just do $value['category] . 我知道我可以只做$value['category]

But that's not what I want to achieve / understand. 但这不是我想要实现/理解的。 I would like the resultset not to be an array of arrays. 我希望结果集不是数组数组。

try 尝试

foreach($result as $key => $value ) {
  echo $value['category'].'<br/>';
}

Alternative 另类

foreach($result as $k)
{
    echo $k['category'];
}

The foreach loop splits up your array into key, value pairs. foreach循环将您的数组拆分为键,值对。 The key in your loop is the index of the array, the value is an array containing ID and Category. 循环中的关键是数组的索引,值是包含ID和Category的数组。

To access the category simply do: 要访问类别,只需执行以下操作:

foreach($result as $key => $value ) {
  echo $value['category'].'<br/>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM