用逗号分隔列

时间:2016-04-27 06:02:35

标签: php mysql

我可以用逗号分隔连接列,但是如果第二列上的逗号如何删除? 在下面,我有2列我想加入otot2和otot3 1.如果otot3 null,如何在otot2之后不显示逗号? 2.如果otot2和otot 3为null,如何不显示任何逗号? 3. otot2和otot3灵活(并不总是有数据)

这里是输出查询的PHP代码:

    if(mysqli_num_rows($hasil) > 0)
{   
    $response = array();
    while($data = mysqli_fetch_array($hasil))
    {
        $h['main muscle'] = $data['otot1'];
        $h['other muscle'] = $data['otot2'].', '.$data['otot3'];

        array_push($response, $h);
    }
    $response["success"];
    echo json_encode($response);

1 个答案:

答案 0 :(得分:1)

一个简单的解决方案是 -

$response = array();
while($data = mysqli_fetch_array($hasil))
{
    // other code

    $temp = array($data['otot2'], $data['otot3']); // Store them in array
    $temp = array_filter($temp); // remove empty values
    $h['other muscle'] = implode(',', $temp); // implode them with (,)

    // Other codes

    array_push($response, $h);
}

使用array_filter& implode您不必担心,,因为array_filter会删除空值,如果数组中有 2 值,则表示字符串将,分开,否则不会。

或者你也可以尝试这个

$h['other muscle'] = $data['otot2'];
if($data['otot3'] !== null)
    $h['other muscle'] .= ', ' . $data['otot3']; // Concatenate

Demo

相关问题