Skip to content

Commit 8c5662e

Browse files
committed
add Arrays::columnAsKey
1 parent 2bf8878 commit 8c5662e

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/Arrays.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,21 @@ public static function firstValue(array $array)
4545
return $array[$key];
4646
}
4747

48+
/**
49+
* @param mixed[] $array
50+
* @param string|int $column
51+
* @return mixed[]
52+
*/
53+
public static function columnAsKey(iterable $array, $column): array
54+
{
55+
$result = [];
56+
foreach ($array as $values) {
57+
$result[$values[$column]] = $values;
58+
}
59+
60+
return $result;
61+
}
62+
4863
/**
4964
* @param mixed[] $previous
5065
* @param mixed[] $current
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php declare(strict_types = 1);
2+
3+
use Tester\Assert;
4+
use Utilitte\Php\Arrays;
5+
6+
require __DIR__ . '/../bootstrap.php';
7+
8+
9+
Assert::same([
10+
5 => ['id' => 5],
11+
6 => ['id' => 6],
12+
], Arrays::columnAsKey([
13+
['id' => 5], ['id' => 6],
14+
], 'id'));

0 commit comments

Comments
 (0)