I am working with a multidimensional array that I want to conditionally add keys to and am not getting the output I desire. At the core of the issue is the following code:
$data[$CSVKey] = array (
'key1' => $key1value,
);
$data[$CSVKey] = array (
'key2' => $key2value,
);
What I would expect to happen when I work with the array at a later time is that there would be a multidimensional array with both key 1 and key 2, but I am not getting that. when I work with it, I only see 'key2'. However when I change it to this:
$data[$CSVKey] = array (
'key1' => $key1value,
'key2' => $key2value,
);
I see the array as I desire. Can I not populate a multidimensional array this way?
You are replacing whatever value $data[$CSVKey]
is each time you assign a new array.
You should just continue using your bracket notation to assign your values:
$data[$CSVKey]['key1'] = $key1value;
$data[$CSVKey]['key2'] = $key2value;
Or you could use array_merge()
if you wanted to add more than one element to the array in one call:
$data[$CSVKey] = array_merge($data[$CSVKey], ['key1' => $key1value, 'key2' => $key2value])