从所有列名和值中获取数据属性的更短方法

表 users 有 14 列 - id, src link, title...


function get_atitles(){

    global $db;

    $st = $db->query("select * from users order by name asc");

    $arr = $st->fetchAll();

    $ht = '';

    foreach($arr as $el){

        $ht .= "<div class='atitle' data-id= " . $el['id'] . " data-src='" . $el['src'] . "... and so on for all of the 14 columns...>" . $el['title'] . "</div>\n";

    }

    echo $ht;

}

有没有更短的方法,像这样:


foreach($arr as $el){

            $ht .= "<div class='atitle' 

                 //foreach column in users $ht .= "data-" . column_name = column_value

            $ht .= ">" . $el['title'] . "</div>\n";

        }


小唯快跑啊
浏览 150回答 1
1回答

HUX布斯

也许是这样的:function get_atitles(){&nbsp; &nbsp; global $db;&nbsp; &nbsp; $st = $db->query("select * from users order by name asc");&nbsp; &nbsp; $arr = $st->fetchAll(PDO::FETCH_ASSOC);&nbsp; &nbsp; $ht = '';&nbsp; &nbsp; foreach($arr as $el){&nbsp; &nbsp; &nbsp; &nbsp; $ht = $ht . "<div class='atitle' ";&nbsp; &nbsp; &nbsp; &nbsp; foreach($el as $key=>$col)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if($key != 'title')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $ht .= "data-".$key.'="'.$col.'" ';&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $ht.= '>'.$el['title'] . "</div>\n";&nbsp; &nbsp; }&nbsp; &nbsp; echo $ht;}
打开App,查看更多内容
随时随地看视频慕课网APP