Take the 2-minute tour ×

I have a multidimensional array which looks like this:

$orderedList {}
    [0] {
      ["listElemId"] = 1
      ["listElemPoints"] = 6
    [1] {
      ["listElemId"] = 2
      ["listElemPoints"] = 5
    [2] {
      ["listElemId"] = 4
      ["listElemPoints"] = 14
    [3] {
      ["listElemId"] = 3
      ["listElemPoints"] = 14

What I do is to give the 'list elements' (i.e. the root elements of the array; [0], [1] and so on) a new sub element called ['listElemOrderPlace'], and give it a placing depending on the points.

This works fine, except when it comes to list elements that has the same amount of points. In this case I want to give them the same placing, (i.e. the same number in ['listElemOrderPlace']). Here's where I need help.

The code below should work (I can't see why it shouldn't), but something is wrong. When I echo out the last list element's points it's empty, even though it's actually not (it get stored in the db and so on). The only time it should be empty is the first 'round' in the loop, because $j refers to -1.

What am I doing wrong?

    $j = -1;
    for ($i = 0; $i < count($orderedList); $i++) {

        echo $orderedList[$i]['listElemPoints']; // 6, 14, 14
        echo $orderedList[$j]['listElemPoints']; // Empty all the time (?)

        if ($orderedList[$i]['listElemPoints'] = $orderedList[$j]['listElemPoints']) {
            $orderedList[$i]['listElemOrderPlace'] = $orderedList[$j]['listElemOrderPlace'];
        else {
            $orderedList[$i]['listElemOrderPlace'] = $i+1;
        $j += 1;
share|improve this question

closed as too localized by PeeHaa, tereško, lc., BNL, RichardTheKiwi Nov 2 '12 at 18:25


add comment

2 Answers

up vote 1 down vote accepted

The code you have is prone to error, you first need to sort the array based on the listElemPoints:

uasort($orderedList, function($a, $b) {
  return $a['listElemPoints'] > $b['listElemPoints'];

After this you can write a simple loop to add the listElemOrderPlace:

$i = 1;
foreach ($orderedList as &$ol) {
  $ol['listElemOrderPlace'] = (!isset($lastCount) || $ol['listElemPoints'] !== $lastCount) ? $i++ : $i;
  $lastCount = $ol['listElemPoints'];
share|improve this answer
The first sort is done earlier in the code, but hey. Thanks a lot for this! Really helped me out :) –  holyredbeard Nov 2 '12 at 10:34
add comment

You are assigning a value in your if:


Use this instead:

if ($orderedList[$i]['listElemPoints'] == $orderedList[$j]['listElemPoints']) {
share|improve this answer
Ah, of course! Been up to many hours ;) Thanks! –  holyredbeard Nov 2 '12 at 10:23
add comment
