adding ArrayKeysSort to the Sorting dir

This commit is contained in:
Brandon Johnson 2022-07-24 02:05:53 -06:00
parent 35ed4625eb
commit 11e22b312f
4 changed files with 77 additions and 4 deletions

View File

@ -38,6 +38,7 @@
* [Upperbound](./Searches/UpperBound.php)
## Sorting
* [Arraykeyssort](./Sorting/ArrayKeysSort.php)
* [Bubblesort](./Sorting/BubbleSort.php)
* [Bubblesort2](./Sorting/BubbleSort2.php)
* [Countsort](./Sorting/CountSort.php)
@ -72,8 +73,7 @@
* Searches
* [Searchestest](./tests/Searches/SearchesTest.php)
* Sorting
* [Arraykeyssorttest](./tests/sorting/arrayKeysSortTest.php)
* Sorting
* [Arraykeyssorttest](./tests/Sorting/ArrayKeysSortTest.php)
* [Sortingtests](./tests/Sorting/SortingTests.php)
* Strings
* [Stringstest](./tests/Strings/StringsTest.php)

View File

@ -1,4 +1,5 @@
<?php
/**
* Binary search algorithm iterative approach
*

72
Sorting/ArrayKeysSort.php Normal file
View File

@ -0,0 +1,72 @@
<?php
/**
* Sort an "Array of objects" or "Array of arrays" by keys
*/
class ArrayKeysSort
{
public const ORDER_ASC = 'ASC';
public const ORDER_DESC = 'DESC';
/**
* @param $collection
* @param array $keys
* @param string $order
* @param bool $isCaseSensitive
* @return mixed
*/
public static function sort(
$collection,
array $keys,
string $order = self::ORDER_ASC,
bool $isCaseSensitive = false
) {
if (!empty($collection) && !empty($keys)) {
try {
usort(
$collection,
function ($a, $b) use ($keys, $order, $isCaseSensitive) {
$pos = 0;
do {
$key = $keys[$pos];
if (is_array($a)) {
if (!isset($a[$key]) || !isset($b[$key])) {
$errorMsg = 'The key "' . $key
. '" does not exist in the collection';
throw new Exception($errorMsg);
}
$item1 = !$isCaseSensitive
? strtolower($a[$key]) : $a[$key];
$item2 = !$isCaseSensitive
? strtolower($b[$key]) : $b[$key];
} else {
if (!isset($a->$key) || !isset($b->$key)) {
$errorMsg = 'The key "' . $key
. '" does not exist in the collection';
throw new Exception($errorMsg);
}
$item1 = !$isCaseSensitive
? strtolower($a->$key) : $a->$key;
$item2 = !$isCaseSensitive
? strtolower($b->$key) : $b->$key;
}
} while ($item1 === $item2 && !empty($keys[++$pos]));
if ($item1 === $item2) {
return 0;
} elseif ($order === self::ORDER_ASC) {
return ($item1 < $item2) ? -1 : 1;
} else {
return ($item1 > $item2) ? -1 : 1;
}
}
);
} catch (Exception $e) {
echo $e->getMessage();
die();
}
}
return $collection;
}
}

View File

@ -1,7 +1,7 @@
<?php
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../sorting/arrayKeysSort.php';
require_once __DIR__ . '/../../Sorting/ArrayKeysSort.php';
use PHPUnit\Framework\TestCase;
@ -67,4 +67,4 @@ class arrayKeysSortTest extends TestCase
$this->assertEquals($result3, $test3);
$this->assertEquals($result4, $test4);
}
}
}