简体   繁体   中英

PHP storing a two dimension array from MySQL query

I have a simple question. I have an array that has two columns (id, name) that is a result of a MySQL query. I want to store the result of the query into a array variable so i can access each element when i need to.

I am able to store a one dimension array like the following:

    $array = array();
    while($row = mysqli_fetch_assoc($result))
    {
        $array[] = $row['name'];
    }

How can I store and access a two dimensional array? Also is it best to use a for loop or while loop to store these?

Don't specifically store the index of $row but rather store the whole row.

$array = array();
while($row = mysqli_fetch_assoc($result))
{
    $array[] = $row;
}

Then $array will have the following structure:

$array = [
    [
       'id'=> ...,
       'name' => ...,
    ],
    ...
];

To initially access all of the results from [mysqli_fetch_assoc][1] you will want to use the while loop like you are, mysqli_fetch_assoc will continue to output results until it doesn't have any more data. Then at that point mysqli_fetch_assoc will return NULL . This will signal to your while loop to stop iterating.

Then to access variables inside of your $array , I recommend using foreach .

You could then do:

foreach ($array as $row) {
  do something with $row['name'] or $row['id']
}

You could also use a for loop, but it takes more work IMO. Compare the above with this alternative:

for ($i = 0; $i < count($array); $i++) {
   $row = $array[$i];
   do something with $row['name'] or $row['id']
}

Simply do this:

$array = array();
while($row = mysqli_fetch_assoc($result))
{
    $array[] = $row;
}

To access your results you can do this:

$firstResultRow = $array[0];
$firstResultName = $array[0]['id'];
$firstResultName = $array[0]['name'];

This will tell you if a particular row exists:

if(isset($array[$x])) {
    $aRow = $row[$x];
    // do stuff with $aRow;
}

This will give you a row count for your array:

$rowCount = count($array);

This will set up a loop through your array:

foreach($array as $index => $row) {
    $id = $row['id']
    $name = $row['name'];
    // $index will have the array index of the current row. 0 -> $rowCount - 1
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM