为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
小唯快跑啊 2023-05-26 15:51:53
表 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";        }
查看完整描述

1 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

也许是这样的:


function get_atitles(){

    global $db;

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

    $arr = $st->fetchAll(PDO::FETCH_ASSOC);

    $ht = '';

    foreach($arr as $el){

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

        foreach($el as $key=>$col)

            if($key != 'title')

                $ht .= "data-".$key.'="'.$col.'" '; 

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

    }

    echo $ht;

}


查看完整回答
反对 回复 2023-05-26
  • 1 回答
  • 0 关注
  • 105 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信