<?php
$names = ['Alice', 'Bob', 'Charlie', 'Alice', 'Dave', 'Alice'];
class Name {
public $name;
public $id;
public function __construct($name, $id = 0) {
$this->name = $name;
$this->id = $id;
}
}
function contains(array $list, $item) {
foreach ($list as $test) {
if ($item->name == $test->name) {
return true;
}
}
return false;
}
// Transform strings -> objects
$mappedNames = array_map(function($name) { return new Name($name); }, $names);
// Deduplicate list
$reducedNames = array_reduce($mappedNames, function($carry, $item) {
if (contains($carry, $item)) {
return $carry;
}
return array_merge($carry, array($item));
}, []);
$idNames = array_map(function($item, $id) {
return new Name($item->name, $id);
}, $reducedNames, range(1, count($reducedNames)));
var_dump($idNames);
preferences:
39.13 ms | 402 KiB | 5 Q