Pete
Pete

Reputation: 170

Printing out associative arrays fetched from SQL database

I have fetched 3 arrays out of a database and put them in associative arrays.

I have learned to print out array as shown below in the comments, but this doesn't seem to work? How can I achieve this?

while($row = mysql_fetch_array($query)) //fetching row in db
{
    $weight = $row['weight'];
    $height = $row['height'];
    $bmi    = round($weight / (pow(($height/100),2)),2); //calculates bmi

    $arrName[] = $row['name']; //main name array
    $arrGender[] = array($row['name'] => $row['gender']); //this and below are associative arrays
    $arrBmi[] = array($row['name'] => $bmi);

}   

foreach($arrName as $key=>$value){
    echo "$value is of gender {$arrGender[$value]} and has a bmi of {$arrBmi[$value]}"; //this line
}

Upvotes: 0

Views: 515

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

This is a weird array to construct and I would simplify it, but use the $key and the name ($value) to access the others:

echo "$value is of gender {$arrGender[$key][$value]}
      and has a bmi of {$arrBmi[$key][$value]}";

To keep it simple just use the array as it comes from the fetch:

$array[] = ['name'   => $row['name'],
            'gender' => $row['gender'],
            'bmi'    => $bmi];

Then in the loop:

echo "{$value['name']} is of gender {$value['gender']}
      and has a bmi of {$value['bmi']}";

Upvotes: 1

Don't Panic
Don't Panic

Reputation: 41810

Like this instead:

$arrGender[$row['name']] = $row['gender']
$arrBmi[$row['name']] =  $bmi);

The way you're doing it, you're assigning multiple sub-arrays to numeric indexes instead of using the name as the key. One thing to watch out for if you end up doing it this way is that if there are non-unique names in your query result, the value at that array key will be overwritten for subsequent duplicate names.

It doesn't look like your really need the second loop, though. You can output the same thing in the while loop as you fetch the results:

while ($row = mysql_fetch_array($query)) //fetching row in db
{
    $bmi = round( $row['weight'] / (pow(( $row['height'] /100),2)),2); //calculates bmi
    echo "$row[name] is of gender $row[gender] and has a bmi of $bmi"; //this line
}

Upvotes: 2

Related Questions