0

So, I'm a PHP rookie that could use some tips when it comes to creating a table and sorting this. I'm not looking for a particular fancy solution but rather just get it to work.

JSON data is imported from API to a variable and I want to print product name and price in a list and statically sort this by product name in alphabetical order, instead of order they appear in array. I have created an HTML table which works fine but I am super stuck when it comes to sorting it. Is it possible to do using perhaps some loops rather than involving JavaScript or similar?

I have the imported and decoded JSON data in $product_data and I'm printing the table like this:

<table id="articles">
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach($product_data as $products) { ?>
        <tr>
            <td><?= $products->product_name; ?></td>
            <td><?= $products->price; ?></td>
        </tr>
        <?php } ?>
    </tbody>
</table>

I find plenty of solutions where you can do this sorting dynamically using JS or solutions to sort when connected to a SQL DB, but I just simply want it to show in alphabetical order with no user interaction.

Thanks

emmab
  • 5
  • 1
  • 1
    Check out the javascript plugin DataTables. It allows you to sort, search, and paginate tables fairly easily and with no user interaction. If you want a PHP based solution, you can sort the array by product name in PHP [in several ways](https://stackoverflow.com/questions/2699086/how-to-sort-multi-dimensional-array-by-value) – GrumpyCrouton Sep 23 '20 at 14:47

1 Answers1

0

Just before your foreach loop, you can sort your array using usort function. This function allows you to sort your array, using your own function:

usort( $product_data, fn($a,$b) => strcmp($a->product_name, $b->product_name) );

And by the way: I think it will be good idea to rename $products variable in your forach loop to $product, because it stands for a single object (single product).

Przemysław Niemiec
  • 1,704
  • 1
  • 11
  • 14