Skip to content

Instantly share code, notes, and snippets.

@lov3catch
Created November 7, 2022 12:54
Show Gist options
  • Save lov3catch/d32546c2a7708ca39725da8173ea2761 to your computer and use it in GitHub Desktop.
Save lov3catch/d32546c2a7708ca39725da8173ea2761 to your computer and use it in GitHub Desktop.
Unique array by multiple fields
<?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