Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

php foreach with multidimensional array

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...