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

如何在php中使用implode获取数据库表的列名

如何在php中使用implode获取数据库表的列名

PHP
幕布斯7119047 2021-06-16 13:08:13
我想获取列的列表而不是 中的行implode,但是它给了我一个错误,但是当我使用数组的索引号时给了我一行的结果。<?php// this is the database connection$session_id = session_start();$con = mysqli_connect("localhost", "root", "", "ecommerce");?>    <!DOCTYPE html>    <html>    <head>        <title>array</title>    </head>    <body><?php$sql_select = "SELECT * FROM cart";$run_select = mysqli_query($con, $sql_select);$datas = [];if(mysqli_num_rows($run_select) > 0) {    while($show = mysqli_fetch_assoc($run_select)) {        $id[] = $show;    }}$avengers = implode(",", $id['1']);// i want to echo out the columns this is giving me the rowsecho $avengers;
查看完整描述

1 回答

?
摇曳的蔷薇

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

while ($show = mysqli_fetch_assoc($run_select)) {


      $id[] = $show;

     }


$avengers = array_column($id, 'COLUMN_NAME');


print_r($avengers);

它将表或数组中的列名/变量名作为字符串返回一个简单的数组,这是我动态构建 MySQL 查询所需的。


解释:-


<?php

// An array that represents a possible record set returned from a database

$a = array(

  array(

    'id' => 5698,

    'first_name' => 'Peter',

    'last_name' => 'Griffin',

  ),

  array(

    'id' => 4767,

    'first_name' => 'Ben',

    'last_name' => 'Smith',

  ),

  array(

    'id' => 3809,

    'first_name' => 'Joe',

    'last_name' => 'Doe',

  )

);


$last_names = array_column($a, 'last_name');

print_r($last_names);

?>

输出:


Array

(

  [0] => Griffin

  [1] => Smith

  [2] => Doe

)


查看完整回答
反对 回复 2021-06-25
  • 1 回答
  • 0 关注
  • 212 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号