0

My array:

Array
(
[0] => stdClass Object
    (
        [questionID] => 588
        [answer] => extremely-likely
        [count] => 2
        [percent] => 95%
    )

[1] => stdClass Object
    (
        [questionID] => 588
        [answer] => extremely-unlikely
        [count] => 2
        [percent] => 95%
    )

[2] => stdClass Object
    (
        [questionID] => 588
        [answer] => likely
        [count] => 1
        [percent] => 48%
    )

[3] => stdClass Object
    (
        [questionID] => 588
        [answer] => neither
        [count] => 1
        [percent] => 48%
    )

[4] => stdClass Object
    (
        [questionID] => 588
        [answer] => unsure
        [count] => 1
        [percent] => 48%
    )

)

I have managed to pull back the data I want to display however, when I loop through each of my questions I want to display them in a specific order.

The order is:

Extremely Likely

Likely

Neither

Unlikely

Extremely unlikely

Unsure

This is because I want my table to look like below:

enter image description here

But at the moment it looks like this.

enter image description here

Sometimes not all of these questions will be there, so if someone hasn't answered extremely likely then that will not be in the array. In that case it will need to default to the next in the list.

Jason
  • 15,017
  • 23
  • 85
  • 116
Matthew Smart
  • 1,301
  • 4
  • 21
  • 37
  • 1
    instead of `extremely-likely` or `likely` kust store a numeric value so you can sort – lschmierer Jun 29 '15 at 12:19
  • 1
    If you're getting this from a database, you should sort it in the database. – deceze Jun 29 '15 at 12:20
  • check this [here](http://sandbox.onlinephpfunctions.com/code/0a99780e7e42362f8b89364184908ea59c34738e) – viral Jun 29 '15 at 12:35
  • @Viral Don't `return $a->index > $b->index`, instead `return $a->index - $b->index`. – deceze Jun 29 '15 at 12:37
  • Thanks this did it perfect for me! – Matthew Smart Jun 29 '15 at 12:40
  • @deceze i'll keep that in mind, but this thing works, can you tell me a case when this fails, i'm curious though – viral Jun 29 '15 at 12:41
  • 1
    @Viral You're supposed to return a value `< 0`, `0` or `> 0` for `usort` to do its job correctly. You're only ever returning `0` or `1` (`false` or `true`). I don't know whether this would ever cause the sorting to be *incorrect*, but at least it may take a lot *longer* to sort due to it having to repeat comparisons. – deceze Jun 29 '15 at 12:45

0 Answers0