简体   繁体   中英

Sorting HTML table with JSON data in alphabetical order

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM