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

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备