Accessing values from a multidimensional array in PHP

65 views Asked by At

In my PHP application, I need to take a multidimensional array and extract values in a for loop. The query will always return 9 rows.

$w = mysqli_query($con,"SELECT age, percent FROM drive03_2_monthly_income WHERE birthYear='1956' AND (age LIKE '%.00%') ORDER BY birthYear,age ");

$row = mysqli_fetch_array($w);
    for($n=0;$n<9;$n++) {
        echo $row[$n]->age." -- ".$row[$n]->percent."<br />";
        }

When I run this, I get the data I want in $w, but having a problem extracting values in the loop.

2

There are 2 answers

0
pedram shabani On

here you are.

<?php
$w = mysqli_query($con,"SELECT age, percent FROM drive03_2_monthly_income WHERE birthYear='1956' AND (age LIKE '%.00%') ORDER BY birthYear,age ");
while ($row = mysqli_fetch_array($w, MYSQLI_ASSOC))
{ 
     echo $row['age']->age." -- ".$row['percent']->percent."<br />";  
}
?>
0
kchason On

The problem is that mysqli_fetch_array() gets a single row. You have a few options for next steps.

Option 1 - Use mysqli_fetch_array() in a loop:

while($row = mysqli_fetch_array($w)){
    // Do something with your associative row data
    echo $row['age'];
}

Option 2 - Use mysqli_fetch_object() in a loop:

while($row = mysqli_fetch_object($w)){
    // Do something with your object row data
    echo $row->name;
}

Option 3 - Use mysqli_fetch_all()

foreach(mysqli_fetch_all($w, MYSQLI_ASSOC) as $row){ 
    // Do something with your associative row data
    echo $row['age'];
}

This is not recommended, as quoted on the documentation.

As mysqli_fetch_all() returns all the rows as an array in a single step, it may consume more memory than some similar functions such as mysqli_fetch_array(), which only returns one row at a time from the result set. Further, if you need to iterate over the result set, you will need a looping construct that will further impact performance. For these reasons mysqli_fetch_all() should only be used in those situations where the fetched result set will be sent to another layer for processing.