I'm reading data from a csv using fgetcsv
and the output is like this:
Array(
[0] => Array
(
[0] => NUMBER
[1] => CODE
[2] => DESCRIPTION
)
[1] => Array
(
[0] => 19
[1] => ABC
[2] => RANDOM DESC
)
[2] => Array
(
[0] => 56
[1] => DEF
[2] => ANOTHER DESC
)
)
but since I'll do some searching based on the number I think memory wise I'd need an array like this instead:
Array(
[19] => Array
(
[CODE] = ABC
[DESCRIPTION] = RANDOM DESC
)
[56] => Array
(
[CODE] = DEF
[DESCRIPTION] = ANOTHER DESC
)
)
Is this the best approach or there might be something better? Also... Is there a function to do this? I'm not very PHP savy so.. please bear with me.
Using array_reduce
can make this easy for you
$result = array_reduce(array_slice($data, 1), function($ys, $x) {
list($number, $code, $description) = $x;
$ys[intval($number)] = array('CODE' => $code, 'DESCRIPTION' => $description);
return $ys;
}, array());
var_dump($result);
Output
array(2) {
[19]=>
array(2) {
["CODE"]=>
string(3) "ABC"
["DESCRIPTION"]=>
string(11) "RANDOM DESC"
}
[56]=>
array(2) {
["CODE"]=>
string(3) "DEF"
["DESCRIPTION"]=>
string(12) "ANOTHER DESC"
}
}