Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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

share|improve this question
1  
Why would you need a second foreach? You have all your variables ready using only one loop, you can simply access them as $value['id'], etc. –  jeroen Jun 20 '11 at 15:29

8 Answers 8

up vote 39 down vote accepted

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.

share|improve this answer

You can use array_walk_recursive:

array_walk_recursive($array, function ($item, $key) {
    echo "$key holds $item\n";
});
share|improve this answer
    
Why would you do this over foreach? Seems like a waste of memory, defining anonymous functions for each iteration. –  Brad Jun 20 '11 at 16:12
1  
@Brad, I do not prefer it over foreach in this case, I just wanted to show an alternative. By the way I don't think it wastes much memory, I think PHP defines this function only once, but calls it for every iteration. –  Karolis Jun 20 '11 at 17:54

Example with mysql_fetch_assoc():

while ($row = mysql_fetch_assoc($result))
{
    /* ... your stuff ...*/
}

In your case with foreach, with the $result array you get from select():

foreach ($result as $row)
{
    /* ... your stuff ...*/
}

It's much like the same, with proper iteration.

share|improve this answer

This would have been a comment under Brad's answer, but I don't have a high enough reputation.

Recently I found that I needed the key of the multidimensional array too, i.e., it wasn't just an index for the array, in the foreach loop.

In order to achieve that, you could use something very similar to the accepted answer, but instead split the key and value as follows

foreach ($mda as $mdaKey => $mdaData) {
    echo $mdaKey . ": " . $mdaData["value"];
}

Hope that helps someone.

share|improve this answer

Wouldn't a normal foreach basically yield the same result as a mysql_fetch_assoc in your case?

when using foreach on that array, you would get an array containing those three keys: 'id','firstname' and 'lastname'.

That should be the same as mysql_fetch_assoc would give (in a loop) for each row.

share|improve this answer
    
it's true, but as I said the array is multidimensional and I don't know how to loop through it like foreach( $array as $key => $value ) –  medk Jun 20 '11 at 15:31
    
In your code, it would look like this: foreach ($array as $row) { echo $row['id'] . ": " . $row['firstname'] . ", " . $row['lastname']; } That would yield three lines, showing the ID, firstname and lastname of your results :). And if you want to dynamically loop through all keys+values, you'd pretty much need another foreach. However; usually you write the queries, so you'd know the results, right? –  Yhn Jun 21 '11 at 7:54

Ideally a multidimensional array is usually an array of arrays so i figured declare an empty array, then create key and value pairs from the db result in a separate array, finally push each array created on iteration into the outer array. you can return the outer array in case this is a separate function call. Hope that helps

$response = array();    
foreach ($res as $result) {
        $elements = array("firstname" => $result[0], "subject_name" => $result[1]);
        array_push($response, $elements);
    }
share|improve this answer
    
It might be helpful to give a blurb as to why this is an answer. –  Popo Feb 19 at 17:15
    
well Popo, ideally a multidimensional array is usually an array of arrays so i figured declare an empty array, then create key and value pairs from the db result in a separate array, finally push each array created on iteration into the outer array. you can return the outer array in case this is a separate function call. Hope that helps –  Poly Feb 19 at 20:24

With arrays in php, the foreach loop is always a pretty solution.
In this case it could be for example:

foreach($my_array as $number => $number_array)
    {
    foreach($number_array as $data = > $user_data)
        {
            print "Array number: $number, contains $data with $user_data.  <br>";
        }
    }
share|improve this answer
foreach ($parsed as $key=> $poke)
{
    $insert = mysql_query("insert into soal 
                          (pertanyaan, a, b, c, d, e, jawaban)
                          values
                          ('$poke[question]',
                          '$poke[options][A]',
                          '$poke[options][B]',
                          '$poke[options][C]',
                          '$poke[options][D]',
                          '$poke[options][E]',
                          '$poke[answer]')");
}
share|improve this answer
    
This is not secure! You must escape data prior to use in an SQL query. The best solution is to use prepared/parameterized queries. –  Brad Aug 4 '13 at 21:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.