dongyanju1094 2013-01-29 02:02
浏览 36
已采纳

php数组在while循环中复制格式

I want to output the result of a query so that the format is the same as:

$links = array(
'Link 1' => '/link1',
'Link 2' => '/link2'
);

So the query is

$query = "SELECT * FROM link";
$result = mysql_query($query, $connection) or die(mysql_error());
$row = mysql_fetch_assoc($result)

The field that need to be output are:

$row['link_title'] and $row['url']
  • 写回答

3条回答 默认 最新

  • doushen1026 2013-01-29 02:33
    关注

    This is probably a bit more complex then desired or necessary but would this work for you:

    $a = 0;
    while ($row = mysql_fetch_assoc($result)) {
        foreach ($row as $k => $v) {
            // Assumes table column name is 'link_title' for the link title
            if ($k == 'link_title') {$title[$a] = $v;} 
            // Assumes table column name is 'url' for the URL
            if ($k == 'url') {$url[$a] = $v;}
        }
        $a++;
    }
    $i = 0;
    foreach ($title as $t) {
        $links[$t] = $url[$i];
        $i++;
    }
    print_r($links);
    

    As @Class stated, if the link_title's never repeat than you could do something like this:

    while ($row = mysql_fetch_assoc($result)) {
        $array[$row['link_title']] = $row['url'];
    }
    

    Since the link_title's were unique both processes output:

    Array ( 
        [Moxiecode] => moxiecode.com 
        [Freshmeat] => freshmeat.com 
    )
    

    Database table + contents:

    id | link_title |     url       |
    ---+------------+---------------|
    1  | Moxiecode  | moxiecode.com |
    ---+------------+---------------|
    2  | Freshmeat  | freshmeat.com |
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏