Search code examples
javascriptphpjqueryhtml-tableresultset

How to go over an array result again in order to arrange (by one of the fields) the result into a table in PHP


I have to do a "detailed report" ordered by location, provider or asset description the thing is, although i get the proper result I'd like to display results like

Location 1:

Table here with assets located in that location

Location 2:

Table with assets located in this location...

Same with providers and descriptions...

My PHP and other languages knowledge is limited. So, I thought of doing something like...

Get the array (the full array not just a row) and then checking if the location in array[i] is equal to array[i+1] then print a <td> with the row data otherwise ending that table and then creating a new

Location:

and finally another table with the rows that match that location...

How can i do this in PHP?

Examples:

This what I currently have

This is what I'd like to do

This is what i'm doing in PHP

<?php

echo "<table>
        <thead>
            <tr>
                <th></th>
                <th>Ubicaci&oacute;n</th>
                <th>C&oacute;digo</th>
                <th>Descripci&oacute;n</th>
                <th>Costo Adquisici&oacute;n</th>
                <th>Saldo a Depreciar de Activos</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <tr>";
while($row = odbc_fetch_array($result)){
    echo"<td></td>
        <td><b>".$row["Ubicacion_actual"]."</b></td>
        <td>".$row["Activo"]."</td>
        <td>".$row["Descripcion"]."</td>
        <td>".number_format($row["Costo_Adquisicion"],4)."</td>
        <td>".number_format($row["Saldo_sin_depreciar"],4)."</td>
        <td></td>

        </tr>"; 
}
echo "</tbody>

    </table>";
odbc_close($dbhandle);
?>

Solution

  • First you should put all of the data into a local array and then use the local array to deal with it.

    so you could have:

    $theArray = array(); //Array to hold data
    $headerIds = array(); //Array to hold unique id of the records
    while($row = odbc_fetch_array($result)){
        array_push($theArray, $row);
        if(!in_array($row["Ubicacion_actual"], $headerIds))
        {
             array_push($headerIds, $row["Ubicacion_actual"]);
        }
    
    }
    
    odbc_close($dbhandle);
    
    foreach($headerIds as $id)
    {
        //Print the header info
        //...
    
        //Loop through each item in your data array until its id matches the header id
        foreach($theArray as $dataItem)
        {
            if($dataItem["Ubicacion_actual"] == $id) //This line item has the same id as the header
            {
                //Display the table row data
            }
        }
    }