diff --git a/parsecsv.lib.php b/parsecsv.lib.php index beffd1e..4ea9e08 100644 --- a/parsecsv.lib.php +++ b/parsecsv.lib.php @@ -730,6 +730,9 @@ class parseCSV { $this->sort_reverse ? krsort($rows, $sort_type) : ksort($rows, $sort_type); + // Avoid issues with mixing string and integer keys: + $rows = array_values($rows); + if ($this->offset !== null || $this->limit !== null) { $rows = array_slice($rows, ($this->offset === null ? 0 : $this->offset), $this->limit, true); } diff --git a/tests/properties/BaseClass.php b/tests/properties/BaseClass.php new file mode 100644 index 0000000..4d9c420 --- /dev/null +++ b/tests/properties/BaseClass.php @@ -0,0 +1,31 @@ +csv = new parseCSV(); + } + + protected function _compareWithExpected($expected) { + $this->csv->auto(__DIR__ . '/../../examples/_books.csv'); + $actual = array_map(function ($row) { + return $row['title']; + }, $this->csv->data); + $this->assertEquals($expected, $actual); + } +} diff --git a/tests/properties/SortByTest.php b/tests/properties/SortByTest.php new file mode 100644 index 0000000..c26d4bb --- /dev/null +++ b/tests/properties/SortByTest.php @@ -0,0 +1,56 @@ +csv->sort_by = 'rating'; + $this->_compareWithExpected([ + // Rating 0 + 'The Killing Kind', + 'The Third Secret', + + // Rating 3 + 'The Last Templar', + 'The Broker (Paperback)', + 'Without Blood (Paperback)', + + // Rating 4 + 'Deception Point (Paperback)', + 'The Rule of Four (Paperback)', + 'The Da Vinci Code (Hardcover)', + + // Rating 5 + 'State of Fear (Paperback)', + 'Prey', + 'Digital Fortress : A Thriller (Mass Market Paperback)', + 'Angels & Demons (Mass Market Paperback)', + ]); + } + + public function testReverseSortByRating() { + $this->csv->sort_by = 'rating'; + $this->csv->sort_reverse = true; + $this->_compareWithExpected([ + + // Rating 5 + 'Digital Fortress : A Thriller (Mass Market Paperback)', + 'Prey', + 'State of Fear (Paperback)', + 'Angels & Demons (Mass Market Paperback)', + + // Rating 4 + 'The Da Vinci Code (Hardcover)', + 'The Rule of Four (Paperback)', + 'Deception Point (Paperback)', + + // Rating 3 + 'The Broker (Paperback)', + 'The Last Templar', + 'Without Blood (Paperback)', + + // Rating 0 + 'The Third Secret', + 'The Killing Kind', + ]); + } +}