如何使用foreach进行数组

时间:2022-01-19 21:36:52

I am trying to display "name" object, but its not working. I seem to be using foreach wrong.. I print_r for $a and it displays the array. Can someone help.

我试图显示“名称”对象,但它无法正常工作。我似乎使用了foreach错误..我打印$ _ $ a它显示数组。有人可以帮忙吗

public function product(){
        $st = $this->db->prepare("select id, name, description, price from deals where quantity > 0 order by id desc");
        $st->execute();

        if ($st->rowCount() == 0){
            echo "There are no products to display";
        } else {
            $a = $st->fetch(PDO::FETCH_OBJ)

            foreach ($a as $products){
                echo $products->name;
            }
        }
    }

2 个解决方案

#1


3  

I don't think you need a foreach loop for what you are doing.

我不认为你需要一个foreach循环来做你正在做的事情。

while( $products = $st->fetch(PDO::FETCH_OBJ) )
{
    echo $products->name;
}

#2


1  

fetch() only returns one row. Your foreach is looping through all the properties of the object returned by fetch(), i.e. the column names.

fetch()只返回一行。你的foreach循环遍历fetch()返回的对象的所有属性,即列名。

#1


3  

I don't think you need a foreach loop for what you are doing.

我不认为你需要一个foreach循环来做你正在做的事情。

while( $products = $st->fetch(PDO::FETCH_OBJ) )
{
    echo $products->name;
}

#2


1  

fetch() only returns one row. Your foreach is looping through all the properties of the object returned by fetch(), i.e. the column names.

fetch()只返回一行。你的foreach循环遍历fetch()返回的对象的所有属性,即列名。