class Item
{
public int $a;
public int $b;
public string $label;
public function __construct(int $a, int $b, string $label)
{
$this->a = $a;
$this->b = $b;
$this->label = $label;
}
public function __toString(): string
{
return "({$this->a}, {$this->b}, {$this->label})";
}
}
// Create dataset
function makeData(): array {
return [
new Item(7, 2, "python"),
new Item(8, 3, "c"),
new Item(3, 5, "c++"),
new Item(4, 1, "c#"),
new Item(3, 2, "java"),
new Item(7, 1, "go"),
new Item(1, 2, "rust"),
];
}
// Sort by A then B
function sortData(array &$data): void
{
usort($data, function (Item $x, Item $y) {
if ($x->a !== $y->a) {
return $x->a <=> $y->a;
}
return $x->b <=> $y->b;
});
}
// Print all items
function printData(array $data): void
{
foreach ($data as $item) {
echo $item . PHP_EOL;
}
}
// Find first item by label
function findByLabel(array $data, string $label): ?Item
{
foreach ($data as $item) {
if ($item->label === $label) {
return $item;
}
}
return null;
}
// Filter by A
function filterByA(array $data, int $value): array
{
return array_filter($data, fn(Item $i) => $i->a === $value);
}
// Main
$data = makeData();
sortData($data);
echo "Sorted data:\n";
printData($data);
echo "\nSearching for 'java':\n";
$found = findByLabel($data, "java");
if ($found !== null) {
echo $found . PHP_EOL;
}
echo "\nFiltering items where A = 7:\n";
$filtered = filterByA($data, 7);
printData($filtered);
/*
run:
Sorted data:
(1, 2, rust)
(3, 2, java)
(3, 5, c++)
(4, 1, c#)
(7, 1, go)
(7, 2, python)
(8, 3, c)
Searching for 'java':
(3, 2, java)
Filtering items where A = 7:
(7, 1, go)
(7, 2, python)
*/