dongzhan8620 2011-02-15 06:39
浏览 37
已采纳

数组声明

I want an array to be declared like $value=array('apple'=>'red', 'mango'=>'yellow'). now i want this values to be fetched from the database. both the apple and the red. suppose this coloures are saved in table called 'colors' and fruits in the table 'fruits', with the color_id. now 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 did'nt work. anybody can help?

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);

thanxx in advance.

  • 写回答

3条回答 默认 最新

  • drake900918 2011-02-15 06:46
    关注

    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:

    • You use id as the primary key in both tables
    • name is the field that contains the color/fruit names

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)