My app has a number of lookup tables stored in a MySQL database that are used for various purposes such as a select
element.
Unfortunately, the query results aren't in an easily-digestible format and need some massaging to be more useful to me.
For example, when you query one of the lookup tables for all values, you get an array like this:
0 => ['level_id' => 1, 'level' => 'Trivial'],
1 => ['level_id' => 2, 'level' => 'Moderate']
2 => ['level_id' => 3, 'level' => 'Challenging'],
3 => ['level_id' => 4, 'level' => 'Formidable']
But for my purposes, this is what I want:
1 => 'Trivial',
2 => 'Moderate',
3 => 'Challenging',
4 => 'Formidable'
(Note that the array keys are the same as the record id).
If the array has more than one additional column, the result will be contained in sub-arrays:
3 => ['level' => 'Challenging', 'description' => 'Foobar'],
4 => ['level' => 'Formidable', 'description' => 'Bazbat']
This is all very trivial, but I wrote this function that I'd like you to review to know if there is a better way to do this in PHP.
The function needs to be generic so it can use any lookup array without having to know the column names.
<?php
// Turn an array into a key=>value pair. Assumes the key is the first item in the sub-array.
public function column_into_keys(array $array): array {
// get the name of the column that contains the record id
$key = key($array[0]);
foreach($array as $row) {
// pop the new key off the top of the array
$id = array_shift($row);
// is there only one item left in the array?
if (count($row) == 1)
// get the first value
$result[$id] = current($row);
else
// get all of the values
$result[$id] = $row;
}
return $result;
}
array_column()
I would need to explicitly indicate the column names, wouldn't I? \$\endgroup\$