0

I have formed this array of objects using this:

foreach($snapdealProductCollection as $snapdealProduct){

            $item = new stdClass();
            $item->id = $snapdealProduct->getId();
            $item->vendortype=2;
            $item->name = $snapdealProduct->getTitle();
            $item->imgsrc = $snapdealProduct->getImageLink();
            $item->price = $snapdealProduct->getEffectivePrice();
            $item->source = "Snapdeal.com";
            $item->redirectUrl = $snapdealProduct->getLink().$affProgram;
            $item->type = $snapedealType[$snapdealProduct->getId()];
            $item->simid = $snapdealsimid[$snapdealProduct->getId()];
            $item->stype = 2;
            $i++;

            array_push($items, $item);
        }

I need to sort firstly by type, then by simid. How should I sort it? Full code:

$unsortedItems = $this->getSimilarItems($pid);

    $vendors=$this->getAllVendors();


    usort($unsortedItems , array($this, "cmp"));

function cmp($a, $b)
{
    return strcmp($a->type, $b->type) || strcmp($a->simid, $b->simid);
}

$unSortedItems is the array returned from the foreach block

androider
  • 982
  • 6
  • 16
  • 32

2 Answers2

0

Basically you compare the first field first and the second field second :-)

function cmp($a, $b) { 
    return strcmp($a->type, $b->type) || strcmp($a->simid, $b->simid);
}

If the first compare returns 0, the second one will be evaluated. You can write the same longer: if first fields are equal, compare another fields, else return the result of the first comparison.

Stanislav Shabalin
  • 19,028
  • 3
  • 18
  • 18
  • doesn't works correctly. Here is the result: sofa----6 sofa----7 table----2 table----3 sofa----8 cushion----9 table----4 cushion----10 All the sofas should be together,all the table and same for the cushion – androider Apr 30 '16 at 18:09
  • Added in the question – androider Apr 30 '16 at 18:24
0

You can use usort() function for this, and your comparison function should be like this:

function cmp($a, $b){
    if(strcmp($a->type, $b->type) == 0){
        if ($a->simid == $b->simid) {
            return 0;
        }
        return ($a->simid < $b->simid) ? -1 : 1;
    }
    return strcmp($a->type, $b->type);
}

usort($unsortedItems , array($this, "cmp"));

Here are the relevant references:

Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37