Added Hyperf\Collection\Arr::shuffleAssoc method (#7141)

This commit is contained in:
Deeka Wong 2024-11-08 10:11:05 +08:00 committed by GitHub
parent 868d333f01
commit 913cd40e86
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 99 additions and 0 deletions

View File

@ -1,5 +1,9 @@
# v3.1.45 - TBD
## Added
- [#7141](https://github.com/hyperf/hyperf/pull/7141) Added method `Hyperf\Collection\Arr::shuffleAssoc`.
## Fixed
- [#7133](https://github.com/hyperf/hyperf/pull/7133) Fixed bug that the connection of migrations cannot work excepted.

View File

@ -490,6 +490,26 @@ class Arr
return $array;
}
/**
* Shuffle an associative array.
*/
public static function shuffleAssoc(array $array, ?int $seed = null): array
{
if (empty($array)) {
return [];
}
$keys = array_keys($array);
$keys = static::shuffle($keys, $seed);
$random = [];
foreach ($keys as $key) {
$random[$key] = $array[$key];
}
return $random;
}
/**
* Sort the array using the given callback or "dot" notation.
*/

View File

@ -228,6 +228,81 @@ class ArrTest extends TestCase
);
}
public function testShuffleAssoc(): void
{
$source = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$shuffled = Arr::shuffleAssoc($source);
$this->assertNotSame($source, $shuffled);
$this->assertSameSize($source, $shuffled);
$this->assertSameSize($source, array_intersect_assoc($source, $shuffled));
$source = ['a', 'b', 'c', 'd'];
$shuffled = Arr::shuffleAssoc($source);
$this->assertNotSame($source, $shuffled);
$this->assertSameSize($source, $shuffled);
$this->assertSameSize($source, array_intersect_assoc($source, $shuffled));
$source = [1, 2, 3, 4];
$shuffled = Arr::shuffleAssoc($source);
$this->assertNotSame($source, $shuffled);
$this->assertSameSize($source, $shuffled);
$this->assertSameSize($source, array_intersect_assoc($source, $shuffled));
}
public function testShuffleAssocWithSeed(): void
{
$source = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$this->assertSame(
Arr::shuffleAssoc($source, 1234),
Arr::shuffleAssoc($source, 1234)
);
$this->assertNotSame(
Arr::shuffleAssoc($source),
Arr::shuffleAssoc($source)
);
$this->assertNotSame(
$source,
Arr::shuffleAssoc($source, 1234)
);
$source = ['a', 'b', 'c', 'd'];
$this->assertSame(
Arr::shuffleAssoc($source, 1234),
Arr::shuffleAssoc($source, 1234)
);
$this->assertNotSame(
Arr::shuffleAssoc($source),
Arr::shuffleAssoc($source)
);
$this->assertNotSame(
$source,
Arr::shuffleAssoc($source, 1234)
);
$source = [1, 2, 3, 4];
$this->assertSame(
Arr::shuffleAssoc($source, 1234),
Arr::shuffleAssoc($source, 1234)
);
$this->assertNotSame(
Arr::shuffleAssoc($source),
Arr::shuffleAssoc($source)
);
$this->assertNotSame(
$source,
Arr::shuffleAssoc($source, 1234)
);
}
public function testEmptyShuffle(): void
{
$this->assertEquals([], Arr::shuffle([]));