PHP输出为分号

时间:2017-07-19 21:07:10

标签: php

我有这段代码:

    // Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT usuarios.id, usuarios.cedula, usuarios.estado, usuarios.nombre, facturas.idcliente, facturas.total\n"
    . "FROM usuarios\n"
    . "LEFT JOIN facturas ON usuarios.id=facturas.idcliente";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "" . $row["id"]. " " . $row["nombre"]. " " . $row["estado"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>

,结果以这种方式显示:

  <00> 000002 Luis Anel Jimenez ACTIVO
  000008 Alexis Gaitan ACTIVO
  000010 LUIS JIMENEZ ACTIVO

我需要显示这样的结果:

  <00> 000002; Luis Anel Jimenez; IDENTIFICADOR_EPAGO; 88191; ESTADO:ACTIVO

我试过这段代码:

   $data = [];
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $data[] = implode(";", [$row["id"],$row["saldo"],$row["nombre"],"IDENTIFICADOR_EPAGO",$row["cedula"],"ESTADO: " . $row["estado"],"\r\n" ]);
    }
    if(count($data)) {
        file_put_contents("epago.txt", $data);
    }
                          } else {
    echo "0 results";
}

但我得到了:

  

000002 ;; Luis Anel Jimenez; IDENTIFICADOR_EPAGO; 88191; ESTADO:ACTIVO;

有没有在第一个变量和最后一个变量;之后删除那个额外的分号ACTIVO;

1 个答案:

答案 0 :(得分:1)

快速,可能有点脏; - )

$data = [];
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        // Dont add the \r\n as array entry, because it will be removed
        // the string is concated and you open it with a texteditor
        // Implode did concat all array values with the sign that you
        // provide with the first parameter. 
        // This will end up in field1;field2;field3;field4;\r\n and so
        // on, this will end up in a trailing ; on your lines
        $data[] = implode(";", [ $row["id"],$row["nombre"],$row["estado"] ]);
    }
    if(count($data)) {
        // Its urgent, that you implode here all "lines" from the array
        // This will prevent, that lines will end with ; because
        // the \r\n will be removed, if you read them with a texteditor
        file_put_contens('path/to/your/file.txt', implode("\r\n", $data));
    }
} else {
    echo "0 results";
}