<?php interface ArrayKeyable { public function toArrayKey(): string|int; } final class MyObject implements ArrayKeyable { public function __construct( public readonly int $id, public readonly string $name, ) {} public function toArrayKey(): string { return $this->name; } } $objects = []; $data = [[1, 'Jane'], [2, 'John'], [3, 'Jake'], [4, 'Jane']]; foreach($data as [$id, $name]) { $object = new MyObject($id, $name); $objects[$object->toArrayKey()][] = $object; // would turn into $objects[$object][] = $object; } var_dump($objects);
You have javascript disabled. You will not be able to edit any code.