T
T
TechNOIR2018-05-29 15:50:55
PHP
TechNOIR, 2018-05-29 15:50:55

PHP. How to clear an array in a loop?

Good afternoon.
Tell me please. How to clear an array in a loop?
There is this code:

<?php
        $host = 'localhost';
        $dbname = 'emr3';
        $user = 'root';
        $pass = '****';
     $result = ''; 
          $DBH = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass); 
 
          //$query = "SELECT * FROM services";
      $query = "SELECT * FROM tevents";
    
          $STH = $DBH->query($query);  
    $test = array();
        $STH->setFetchMode(PDO::FETCH_ASSOC);
    while($row = $STH->fetch()) {
      $tmp = array();
      //echo $row['serv_id'];
      $temp = explode(",", $row['serv_id']);
      //var_dump ($temp);
        foreach ($temp as $key => $value){
        //echo $t;
        $quer = "SELECT * FROM services WHERE ID='".$value."'";
        $ST = $DBH->query($quer); 
        $ST->setFetchMode(PDO::FETCH_ASSOC);
          while($rw = $ST->fetch()){
          $test[] = $rw['servname'];
          }
        }
        //var_dump ($test);
        $result = implode(",", $test);
        echo $row['event_id']." ".$row['event_name']." ".$row['start_date']." ".$row['end_date']." ".implode(",", $test)."<br>";
    }
?>

$result has a floating value depending on the request. This code returns values, but $result is not cleared and adds the old value to the new one.
Now it turns out like this:
199 1111 2018-05-29 15:30:55 2018-05-29 15:30:55 Услуга1,Услуга2
198 Курлык 2018-05-23 08:50:00 2018-05-23 08:50:00 Услуга1,Услуга2,Услуга2,Услуга3
197 2018-05-23 08:50:00 2018-05-23 11:45:00 Услуга1,Услуга2,Услуга2,Услуга3,Услуга1,Услуга3,Услуга2

And it should be:
199 1111 2018-05-29 15:30:55 2018-05-29 15:30:55 Услуга1,Услуга2
198 Курлык 2018-05-23 08:50:00 2018-05-23 08:50:00 Услуга2,Услуга3
197 2018-05-23 08:50:00 2018-05-23 11:45:00 Услуга1,Услуга3,Услуга2

Thanks in advance for your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Entelis, 2018-05-29
@TechNOIR

while($row = $STH->fetch()) {
it's a loop through all the tuples in the response.
immediately after this line add
$test = [];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question