public function testMultiSort() { $this->assertEmpty(ArrayUtils::multiSort($this->_getArrayPreset('empty_array'), 'id')); $collection = $this->_getArrayPreset('2D_collection_5'); $collectionNamed = $this->_getArrayPreset('2D_collection_5_named'); $this->assertCount(count($collection), ArrayUtils::multiSort($collection, 'id')); $this->assertTrue(ArrayUtils::isCollection(ArrayUtils::multiSort($collectionNamed, 'id'))); // make sure the same order $sortedCollection = ArrayUtils::multiSort($collection, 'id'); $this->assertEquals($collection, $sortedCollection); // make sure proper order $sortedCollection = ArrayUtils::multiSort($collection, 'categoryId'); $this->assertEquals('1-3-3-5-5', ArrayUtils::implodeByKey($sortedCollection, 'categoryId', '-')); $sortedCollection = ArrayUtils::multiSort($collection, 'categoryId', true); $this->assertEquals('5-5-3-3-1', ArrayUtils::implodeByKey($sortedCollection, 'categoryId', '-')); $sortedCollection = ArrayUtils::multiSort($collection, 'date'); $this->assertEquals('5-2-1-9-6', ArrayUtils::implodeByKey($sortedCollection, 'id', '-')); $sortedCollection = ArrayUtils::multiSort($collection, 'date', true); $this->assertEquals('6-9-1-2-5', ArrayUtils::implodeByKey($sortedCollection, 'id', '-')); // make sure all keys are intact $sortedCollection = ArrayUtils::multiSort($collectionNamed, 'date', true); foreach ($sortedCollection as $item) { $this->assertArrayHasKey('id', $item); $this->assertArrayHasKey('name', $item); $this->assertArrayHasKey('categoryId', $item); $this->assertArrayHasKey('date', $item); } }
/** * Sort the items based on `orderBy` and `orderDir` parameters. * * @param array $items Items to be sorted. * @param array $params Query params. * * @return array */ protected function sort(array $items, array $params) { if (is_array($params['orderBy'])) { foreach ($params['orderBy'] as $property => $orderDir) { if (is_string($orderDir)) { $property = $orderDir; $orderDir = Knit::ORDER_ASC; } $items = ArrayUtils::multiSort($items, $property, $orderDir === Knit::ORDER_DESC); // memory sorting only supports one level sorting break; } return $items; } $orderDir = isset($params['orderDir']) ? $params['orderDir'] : Knit::ORDER_ASC; return ArrayUtils::multiSort($items, $params['orderBy'], $orderDir === Knit::ORDER_DESC); }