I have data, from HTTP requests, that I am rendering in the form of a table. Right now, I just have it so that the listings are ordered as the for loop processes them, but I want it so that the for loop processes them and then sorts the data according to highest % of weight. Weight is a column header in a table wit h7 other column headers.
Now, this project is in php + html. I have never used php before, so am rather confused with syntax and where to put logic.
I have tried using the sort() and asort() functions in php, but I am clearly putting these things in the wrong order. I feel like what I want to do is: 1) save the output of the for_loop that renders the table in a table format as some data type 2) then sort that data type according to the column of weight in ascending order. 3) display this in a table
Here is some code!
"<div class='last-updated text-left'>" .
"<small>As of <span>$update_date</span></small>" .
"</div>" .
"<table class='ershares-table with-thead'>" .
"<thead><tr>" .
"<th>Company</th>" .
"<th>Weight</th>" .
"<th>Ticker</th>" .
"<th>Market Price</th>" .
"<th>Shares Held</th>" .
"<th>Market Value</th>" .
"<th>CUSIP</th>" .
"</tr></thead> " .
"<tbody>";
for ($i = 0; $i < $for_loop_limit; $i++) :
echo
"<tr>" .
"<td><strong>" . $ers_holdings[$i]["securityDescription"] . "</strong></td>" .
"<td>" . getMarketValuePercentage($ers_holdings[$i]["securityIdentifier"], $ers_holdings[$i]["marketValuePercentage"]) . "%</td>" .
"<td>" . $ers_holdings[$i]["ticker"] . "</td>" .
"<td>" . $ers_holdings[$i]["marketPriceOfSecurity"] . "</td>" .
"<td>" . $ers_holdings[$i]["sharesHeldOfSecurity"] . "</td>" .
"<td>" . $ers_holdings[$i]["marketValueOfHolding"] . "</td>" .
"<td>" . $ers_holdings[$i]["securityIdentifier"] . "</td>" .
"</tr>";
endfor;
echo "</tbody>" .
'</table>' .
I want to sort the table by having the highest value for getMarketValuePercentage...
at the top. Thank you in advance.
Advertisement
Answer
You’re looking for usort()
.
Before doing your foreach
loop, you’ll call something along the lines of:
usort($ers_holdings, function ($a, $b) {
return ($a['securityIdentifier'] <=> $b['securityIdentifier']);
});
which would sort the data in $ers_holdings
based on the ['securityIdentifier']
value.