猿问

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

我想获取列的列表而不是 中的行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 rows

echo $avengers;


幕布斯7119047
浏览 214回答 1
1回答

摇曳的蔷薇

while ($show = mysqli_fetch_assoc($run_select)) {&nbsp; &nbsp; &nbsp; $id[] = $show;&nbsp; &nbsp; &nbsp;}$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(&nbsp; array(&nbsp; &nbsp; 'id' => 5698,&nbsp; &nbsp; 'first_name' => 'Peter',&nbsp; &nbsp; 'last_name' => 'Griffin',&nbsp; ),&nbsp; array(&nbsp; &nbsp; 'id' => 4767,&nbsp; &nbsp; 'first_name' => 'Ben',&nbsp; &nbsp; 'last_name' => 'Smith',&nbsp; ),&nbsp; array(&nbsp; &nbsp; 'id' => 3809,&nbsp; &nbsp; 'first_name' => 'Joe',&nbsp; &nbsp; 'last_name' => 'Doe',&nbsp; ));$last_names = array_column($a, 'last_name');print_r($last_names);?>输出:Array(&nbsp; [0] => Griffin&nbsp; [1] => Smith&nbsp; [2] => Doe)
随时随地看视频慕课网APP
我要回答