0

I have an array of objects containing a number of values. The values are set correctly and the data inside this array is also shown in correct way accoring to the order of objects.

What i would want now ii that the order is changed. In this particular example according to the objects 'Point' value, so the objects with the highest Pointvalue is first and so on...

What I tried to do was finding the object with the highest value, push it in the array and unsetting the original value. And with array_slice getting the relevant array elements in the end.

I also succeeded in the first part, but the problem is I keep finding the same object, so i somehow doesn't remove it from the array.

$max = $obj[0];
    for ($j =0; $j<count($obj)-$j; $j++) {
        for ($i=0; $i<count($names); $i++) {
            if ($max->Point < $obj[$i+1]->Point) {
                $max = $obj[$i+1];
            }
        }
        if ($max->id == $obj[$j]->id) {
            unset($obj[$j]);
        }
        array_push($obj, $max);
    }

I'm not sure you can see through the code and what I'm trying to do, but hopefully someone can and either show my mistake(s), or show others way to accomplish the same?

1

1 Answer 1

1

Try using the usort() function. It allows you to sort the array according to a comparison function that you define.

function lower_points($a, $b) {
    if ($a->Point == $b->Point) return 0;
    else if ($a->Point > $b->Point) return -1;
    else return 1;
}

usort($array_of_objects, lower_points);
Sign up to request clarification or add additional context in comments.

6 Comments

That is quite short for an answer. You should either expand it, or make it a comment instead.
maybe hold off for 30 seconds or so?
Well maybe write a complete answer in the first place, instead of just submitting it premature to be “the first one” …? ;-)
@CBroe Seems pretty explanatory to me. Not sure why more explanation is needed.
@AzizSaleh: He’s edited it now – initially it was just “Try using the usort() function.”, no more, not even a link to the manual.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.