How to transform an array like :
$data = [
['id' => 4, 'value' => 'herp',],
['id' => 7, 'value' => 'derp',],
['id' => 9, 'value' => 'yolo',],
];
to :
$data = [
4 => 'herp',
7 => 'derp',
9 => 'yolo',
];
for
function get_array($data) {
$options = [];
$count = count($data);
for ($i = 0; $i < $count; $i++) {
$options[$data[$i]['id']] = $data[$i]['value'];
}
return $options;
}
foreach
function get_array($data) {
$options = [];
foreach ($data as $d) {
$options[$d['id']] = $d['value'];
}
return $options;
}
array_column/array_combine
function get_array($data) {
$keys = array_column($data, 'id');
$values = array_column($data, 'value');
$options = array_combine($keys, $values);
return $options;
}
Results
| Function | for | foreach | array_column / array_combine |
|---|---|---|---|
| Average in seconds for 1000000 calls | 5.518 | 3.758 | 3.576 |