带有多维数组的php foreach [英] php foreach with multidimensional array

查看:51
本文介绍了带有多维数组的php foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用数据库类来查询 mySQL 的 php 应用程序.

课程在这里:http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/

我对类做了一些调整以满足我的需要,但是有一个问题(可能是一个愚蠢的问题)

当使用 select() 时,它返回一个多维数组,类似于具有 3 个列(id、firstname、lastname)的表:

<前>大批([0] => 数组([id] => 1[名字] => 名字一个[姓氏] => 姓氏一)[1] => 数组([id] => 2[名字] => 名字二[姓氏] => 姓氏二)[2] => 数组([id] => 3[名字] => 名字三[姓氏] => 姓氏三))

现在我想将此数组用作 mysql 结果 (mysql_fetch_assoc).

我知道它可以与 foreach() 一起使用,但这是与简单数组一起使用的.所以我认为我必须为每个 foreach() 重新声明一个新的 foreach(),但我认为这可能会减慢速度或导致更高的服务器负载.

那么如何以最简单的方式将 foreach() 应用于这个多维数组?

谢谢

解决方案

你可以在这里使用 foreach 就好了.

foreach ($rows as $row) {回声 $row['id'];回声 $row['firstname'];回声 $row['lastname'];}

我认为您习惯于使用数字索引(例如 $row[0])访问数据,但这不是必需的.我们可以使用关联数组来获取我们想要的数据.

I'm developing a php app that uses a database class to query mySQL.

the class is here: http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/

I made some tweaks on the class to fit my needs, but there is a problem (maybe a stupid one)

When using select() it returns a multidimensional array like that for a table that has 3 cols (id, firstname, lastname):

Array
(
    [0] => Array
        (
            [id] => 1
            [firstname] => Firstname one
            [lastname] => Lastname one
        )

    [1] => Array
        (
            [id] => 2
            [firstname] => Firstname two
            [lastname] => Lastname two
        )

    [2] => Array
        (
            [id] => 3
            [firstname] => Firstname three
            [lastname] => Lastname three
        )
)

Now I want this array to be used as a mysql result (mysql_fetch_assoc).

I know that it may be used with foreach() but this is with simple arrays. so I think that I have to redeclare a new foreach() withing each foreach(), but I think this could slow down or cause some higher server load.

So how to apply foreach() with this multidimensional array the simplest way?

Thanks

解决方案

You can use foreach here just fine.

foreach ($rows as $row) {
    echo $row['id'];
    echo $row['firstname'];
    echo $row['lastname'];
}

I think you are used to accessing the data with numerical indicies (such as $row[0]), but this is not necessary. We can use associative arrays to get the data we're after.

这篇关于带有多维数组的php foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆