65

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/
*note there are multiple bad practices demonstrated in the tutorial -- it should not be used as a modern guide!

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 that has rows with 3 associative columns (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/flat arrays. I think that I have to redeclare a new foreach() within 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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
medk
  • 9,233
  • 18
  • 57
  • 79
  • 2
    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

13 Answers13

125

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 indices (such as $row[0]), but this is not necessary. We can use associative arrays to get the data we're after.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Brad
  • 159,648
  • 54
  • 349
  • 530
16

You can use array_walk_recursive:

array_walk_recursive($array, function ($item, $key) {
    echo "$key holds $item\n";
});
Karolis
  • 9,396
  • 29
  • 38
  • 1
    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
  • 4
    @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
  • the question asks to use `foreach`.But I think this is more convenient because if you add elements in array(say, you added `age`), you do not have to change `array_walk_recursive` function – ajinzrathod Apr 16 '20 at 08:50
10

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>";
        }
    }
nao_de_naoned
  • 111
  • 1
  • 3
5

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.

arvy3
  • 136
  • 1
  • 9
4

Holla/Hello, I got it! You can easily get the file name,tmp_name,file_size etc.So I will show you how to get file name with a line of code.

for ($i = 0 ; $i < count($files['name']); $i++) {
    echo $files['name'][$i].'<br/>';
}

It is tested on my PC.

Asraful Haque
  • 1,109
  • 7
  • 17
3

To get detail out of each value in a multidimensional array is quite straightforward once you have your array in place. So this is the array:

$example_array = array(
array('1','John','Smith'),
array('2','Dave','Jones'),
array('3','Bob','Williams')
);

Then use a foreach loop and have the array ran through like this:

foreach ($example_array as $value) {
echo $value[0]; //this will echo 1 on first cycle, 2 on second etc....
echo $value[1]; //this will echo John on first cycle, Dave on second etc....
echo $value[2]; //this will echo Smith on first cycle, Jones on second etc....
}

You can echo whatever you like around it to, so to echo into a table:

echo "<table>"
    foreach ($example_array as $value) {
    echo "<tr><td>" . $value[0] . "</td>";
    echo "<td>" . $value[1] . "</td>";
    echo "<td>" . $value[2] . "</td></tr>";
    }
echo "</table>";

Should give you a table like this:

|1|John|Smith   |
|2|Dave|Jones   |
|3|Bob |Williams|
Rmj86
  • 1,140
  • 1
  • 7
  • 9
2

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.

aorcsik
  • 15,271
  • 5
  • 39
  • 49
1

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);
    }
Poly
  • 13
  • 3
  • It might be helpful to give a blurb as to why this is an answer. – Popo Feb 19 '15 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 '15 at 20:24
1

I know this is quite an old answer. Here is a faster solution without using foreach:

Use array_column

print_r(array_column($array, 'firstname')); #returns the value associated with that key 'firstname'

Also you can check before executing the above operation

if(array_key_exists('firstname', $array)){
   print_r(array_column($array, 'firstname'));
}
Rotimi
  • 4,783
  • 4
  • 18
  • 27
0
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]')");
}
Fred Wuerges
  • 1,965
  • 2
  • 21
  • 42
endip
  • 17
  • 1
  • 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 04 '13 at 21:47
  • Move to PDO. You won't need to sanitize your SQL if you use the "prepare" statement according to the specification. Here is an example. $sql = "SELECT firstName, lastName from tbl where id = :id"; $pdo = PDO_Reference(); $stmt = $pdo->prepare($sql); $stmt->execute([':id' => $id]); – Gregory Bologna Jan 08 '19 at 21:49
0

If you need to do string manipulation on array elements, e.g, then using callback function array_walk_recursive (or even array_walk) works well. Both come in handy when dynamically writing SQL statements.

In this usage, I have this array with each element needing an appended comma and newline.

$some_array = [];

data in $some_array
0: "Some string in an array"
1: "Another string in an array"

Per php.net

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

array_walk_recursive($some_array, function (&$value, $key) {
    $value .= ",\n";
});

Result:
"Some string in an array,\n"
"Another string in an array,\n"

Here's the same concept using array_walk to prepend the database table name to the field.

$fields = [];

data in $fields:
0: "FirstName"
1: "LastName"

$tbl = "Employees"

array_walk($fields, 'prefixOnArray', $tbl.".");

function prefixOnArray(&$value, $key, $prefix) { 
    $value = $prefix.$value; 
}

Result:
"Employees.FirstName"
"Employees.LastName"


I would be curious to know if performance is at issue over foreach, but for an array with a handful of elements, IMHO, it's hardly worth considering.

Gregory Bologna
  • 270
  • 1
  • 6
  • 20
0

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.

Yhn
  • 2,785
  • 2
  • 13
  • 10
  • 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 07:54
0

A mysql result set object is immediately iterable within a foreach(). This means that it is not necessary to call any kind of fetch*() function/method to access the row data in php. You can simply pass the result set object as the input value of the foreach().

Also, from PHP7.1, "array destructuring" allows you to create individual values (if desirable) within the foreach() declaration.

Non-exhaustive list of examples that all produce the same output: (PHPize Sandbox)

foreach ($mysqli->query("SELECT id, firstname, lastname FROM your_table") as $row) {
    vprintf('%d: %s %s', $row);
}

foreach ($mysqli->query("SELECT * FROM your_table") as ['id' => $id, 'firstname' => $firstName, 'lastname' => $lastName]) {
    printf('%d: %s %s', $id, $firstName, $lastName);
}

*note that you do not need to list all columns while destructuring -- only what you intend to access


$result = $mysqli->query("SELECT * FROM your_table");
foreach ($result as $row) {
    echo "$row['id']: $row['firstname'] $row['lastname']";
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136