Created
November 7, 2022 12:54
-
-
Save lov3catch/d32546c2a7708ca39725da8173ea2761 to your computer and use it in GitHub Desktop.
Unique array by multiple fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
$input = [ | |
['name' => 'toto', 'type' => '1', 'type2' => '2'], | |
['name' => 'tata', 'type' => '1', 'type2' => '3'], | |
['name' => 'titi', 'type' => '1', 'type2' => '2'], | |
['name' => 'tutu', 'type' => '2', 'type2' => '4'], | |
['name' => 'tete', 'type' => '3', 'type2' => '2'], | |
]; | |
$keys = array_map( | |
static fn(string $key, string $value) => "$key:$value", | |
array_column($input, 'type'), array_column($input, 'type2')); | |
$result = array_values(array_combine($keys, array_values($input))); | |
$expect = [ | |
['name' => 'titi', 'type' => '1', 'type2' => '2'], | |
['name' => 'tata', 'type' => '1', 'type2' => '3'], | |
['name' => 'tutu', 'type' => '2', 'type2' => '4'], | |
['name' => 'tete', 'type' => '3', 'type2' => '2'], | |
]; | |
assert($result === $expect); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment