Skip to content
Advertisement

How to sort an array based on another value?

So I am pretty lost here because I don’t know what my object looks like (not sure why I can’t do print_r() to print the object).

Basically from the below code, I need to sort the reviews which is $_reviews based on $percent_avg. I got the $percent_avg value from a multiple for loops and that’s what complicates things. I am not sure how can I make a new sorted array based on that $percent_avg variable.

JavaScript

I have attempted the above code to sort the reviews, what I think is that I can make a new array for a sorted $percent_avg and compare that value with the $_reviews object? But with this, it will be pretty slow?

JavaScript

The above is just an idea and it is not working.

I am still new to PHP, so any suggestions/helps will be appreciated. Thank you.

Advertisement

Answer

If you want to sort $_reviews based on the sum of each review’s getRatingsVotes()getPercent(), you can use usort():

JavaScript

This may be slow if $_reviews contains many elements, or if individual reviews tend to contain many votes. You can speed it up by caching $a_total and $b_total, and using those cached numbers where possible:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement