从多行中获取一列值,并在php中的echo / print_r中添加逗号

时间:2019-01-25 05:50:04

标签: php arrays

我正在尝试获取多行,并且只希望从每个获取的行中显示一个相应的列值(同时用逗号或空格隔开)。

我尝试了多种方法(带注释的代码),但没有任何反应。

$query="SELECT tests FROM p_tests WHERE app_id='$id' ";
        //SELECT STRING_AGG(TaskName, ', ') 
        // FROM Tasks;
    $run=mysqli_query($db,$query);
    while ($run=mysqli_fetch_array($res)) {
      // $tname=$run['tests']; 
      // echo $tname;

      // $Var=implode(', ',$run['tests']);
      // echo $Var;


        // $run = implode(', ', array_column($run,0));
        // echo $run;

        //$test = array_column($run, 'tests');
        // print_r($run);
        // echo $run;
}
?>

2 个答案:

答案 0 :(得分:0)

如果 $ run ['tests'] 是要从每一行中获取的特定列,请使用以下代码:

$query="SELECT tests FROM p_tests WHERE app_id='$id' ";
        //SELECT STRING_AGG(TaskName, ', ') 
        // FROM Tasks;
    $run=mysqli_query($db,$query);
    $arr = [];
    while ($run=mysqli_fetch_array($res)) {
          $tname=$run['tests'];
          $arr[] = $tname; 
    }
    $new_arr_comma = implode(',',$arr); // For comma seperated;
    $new_arr_space = implode(' ',$arr); // For space seperated;

    print_r($new_arr_comma);
    print_r($new_arr_space);
?>

答案 1 :(得分:0)

类似....

<?php

$link = mysqli_connect ( 'localhost', 'user', 'pass', 'db' );

if ( $result = mysqli_query ( $link, "SELECT tests FROM p_tests WHERE app_id = '" . $id . "';", MYSQLI_USE_RESULT ) )
{
    $data = array ( );

    while ( $row = mysqli_fetch_assoc ( $result ) )
    {
        $data[] = $row['tests'];
    }

    mysqli_free_result ( $result );

    echo implode ( ', ', $data );
}

?>