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
Looping through multidimensional arrays Just as with regular, single-dimensional arrays, you can use foreach to loop through multidimensional arrays. To do this, you need to create nested foreach loops — that is, one loop inside another: The outer loop reads each element in the top-level array.
For example, write the foreach loop where the $bikes variable is the array. Set the $number variable as key and the $bike variable as value. Next, write another foreach loop inside the just created loop. In the nested loop, write the $bike variable as an array and set the $num and $value as key and value.
PHP foreach modify array elementsBy using the ampersand operator (&), the foreach statement works with a reference to the array element. <? php $vals = [1, 2, 3, 4, 5]; foreach ($vals as &$val) { $val *= 2; } print_r($vals); In the example, we go through the array of integers and multiply each element by two.
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.
You can use array_walk_recursive
:
array_walk_recursive($array, function ($item, $key) { echo "$key holds $item\n"; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With