Check for identical strings in a while loop and put them in a separate table

I would like to check all equal rows first and then put them in a separate table

this is what i have done so far

table1
    |   id  |   name    |
    |   1   |   JUS     |
    |   1   |   NUM     |
    |   2   |   SET     |


/**
 * this is the the query for retrieving the data
 * from table1
 */
$query="SELECT 
            id,
            name
        FROM 
            table1
        order by 
            id";

$results=$db->query($query);

$previous='';
while($row=mysqli_fetch_assoc($results)){
    $id=$row['id'];
    $name=$row['name'];

    if($id==$previous){

        /**
         * This is where i am stucked up
         */
        $current='';

    }
    $previous=$id;
}

      

I want to get id s 1

as value into one html table like below

    first html table
    ID      |   1   |   1   |
    Name    |   JUS |   NUM |

      

and also get id c 2

as value to another html table. Thus, we will get separate tables if they id

do not match

  second html table
    ID      | 2     |
    Name    | SET   |

      

Any idea on how to do this is appreciated. Thank.

+1


source to share


1 answer


You can simply collect all of them first in the container, using them id

as your keys so that they are grouped. After that, just print them accordingly:

$data = array();
while($row = $results->fetch_assoc()){
    $id = $row['id'];
    $name = $row['name'];
    $data[$id][] = $name; // group them
}

foreach($data as $id => $values) {
    // each grouped id will be printed in each table
    echo '<table>';
    // header
    echo '<tr>';
        echo '<td>ID</td>' . str_repeat("<td>$id</td>", count($values));
    echo '</tr>';

    echo '<tr>';
    echo '<td>Name</td>';
    foreach($values as $value) {
        echo "<td>$value</td>";
    }
    echo '</tr>';

    echo '</table><br/>';
}

      



This will work if these fields are the same, if you want something more dynamic, you need a different dimension, and instead of just pushing, name

you need to push the entire line:

$results = $db->query('SELECT id, name, age FROM table1');

$data = array();
while($row = $results->fetch_assoc()){
    $id = $row['id']; unset($row['id']);
    $data[$id][] = $row; // group them
}

$fields = array('name', 'age');

foreach($data as $id => $values) {
    // each grouped id will be printed in each table
    echo '<table>';
    // header
    echo '<tr>';
        echo '<td>ID</td>' . str_repeat("<td>$id</td>", count($values));
    echo '</tr>';

    foreach($fields as $field) {
        // construct td
        $temp = '';
        echo "<tr><td>$field</td>";
        for($i = 0; $i < count($values); $i++) {
            $temp .= '<td>' . $values[$i][$field] . '</td>';
        }
        echo $temp; // constructed td
        echo '</tr>';

    }

    echo '</table><br/>';
}

      

+3


source







All Articles