phpmysqlassociative-array

How to populate a flat associative array while looping query results?


I want an array to be declared like $value=array('apple'=>'red', 'mango'=>'yellow').

I want this values to be fetched from the database -- both the apple and the red.

Suppose these colours are saved in table called 'colors' and fruits in the table 'fruits', with the color_id.

How to fetch them and put inside this array?

I tried to put the codes in side the bracket like array (code to fetch) but it didn't work.

table -> fruit(fruit_id, color_id, fruit_name) table -> color(color_id, color_name)

$result = mysql_query("select * from fruit_table");
while ($row = mysql_fetch_array($result)) {
    $row_color - mysql_fetch_array(mysql_query("select color_name from colors where color_id=$row['color_id']"));
    $val[] = "$row['fruit_name'] => $row_color[color_name]";     
} 
$data = implode(",", $val);
$value = array($data);

Solution

  • There are two things you will have to do.

    1. Perform a query to get the required information from the database.
    2. Turn the result from the query into the format you want.

    Here's some example code (assuming you have already made a successful connection to the database).

    Assumptions I've made on your database schema are:

    If they are correct it should work, otherwise minor adjustments are required to the query

    $result = mysql_query('
        SELECT fruits.name as fruit, colors.name as color 
        FROM fruits 
        JOIN colors 
        ON fruits.color_id = color.id');
    
    if (!$result) {
        die(mysql_error());
    }
    
    $value = array();
    
    while ($row = mysql_fetch_assoc($result)) {
        $value[$row['fruit']] = $row['color'];
    }
    
    mysql_free_result($result);