uasort将自定义字段保留为未排序

时间:2017-07-21 11:00:03

标签: php sorting phpunit

所以我有一个功能

namespace MyApp\MyBundle\Classes;

class FieldSorter{

    public function sortFieldsByIndex($fields){

        $fields->uasort(function ($fa, $fb) {
            if ($fa->getIndex() == $fb->getIndex()) {
                return 0;
            }
            return ($fa->getIndex() < $fb->getIndex()) ? -1 : 1;
        });
       return $fields
    }
}     

在使用数组对象迭代器时工作并对字段进行排序。当我尝试phpunit测试它时,

namespace MyApp\MyBundle\Classes;

use MyApp\MyBundle\Classes\Field;

class FieldSorterTest extends TestCase {

        protected $object;
        protected $field1;
        protected $field2;
        protected $fields = array();

    public function testSortFieldsByIndex(){

         $this->field1 = new Field();
         $this->field1->setIndex(4);


         $this->field2 = new Field();
         $this->field2->setIndex(3);

         $fields = new \ArrayObject(array($this->field1, $this->field2));
         $this->object = new FieldSorter();
         $fieldSorted = $this->object->sortFieldsByIndex($fields);
         // pre test
         echo $fieldSorted[0]->getIndex();
    }

}

回声产生4,而不是3 ....

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

echo $fieldSorted[0]->getIndex();

是问题(感谢评论中的帮助)。相反,如果我做

$count = 3;
foreach($fieldsSorted as $fieldSorted){
    $this->assertEquals($count, $fieldSorted->getIndex());
    $count++;
}

然后我通过测试,因为后面的索引真的确实来了(例如3到4)