I need to write an array in a CSV file where column order must not be changed. But I want to reduce column titles to a length of max 64 chars. To make the question more general, let's take a simple example :
$array = array(
'A te' => 'foo A',
'Q test' => 'foo Q',
'Z test' => 'foo Z',
);
var_dump($array);
Give :
array (size=3)
'A te' => string 'foo A' (length=5)
'Q test' => string 'foo Q' (length=5)
'Z test' => string 'foo Z' (length=5)
Now, I want to rename the "Q test" key to "Q tes". If I do :
$swap = $array["Q test"];
unset($array["Q test"]);
$array["Q tes"] = $swap;
var_dump($array);
Displays :
array (size=3)
'A te' => string 'foo A' (length=5)
'Z test' => string 'foo Z' (length=5)
'Q tes' => string 'foo Q' (length=5)
The column's position changed, that's not what I was looking for.
I solved my problem by using (here, reducing keys to 5 chars) :
$keys = array_keys($array);
$values = array_values($array);
$count = count($keys);
for ($i = 0; ($i < $count); $i++)
{
if (mb_strlen($keys[$i]) > 5)
{
$keys[$i] = mb_substr($keys[$i], 0, 5);
}
}
$array = array_combine($keys, $values);
var_dump($array);
Outputs:
array (size=3)
'A te' => string 'foo A' (length=5)
'Q tes' => string 'foo Q' (length=5)
'Z tes' => string 'foo Z' (length=5)
But this looks very resources-devour... I do need to execute such a code on each of my rows, and I have from 10k to 100k rows.
Is there a simpler way to rename array keys without moving them?