Reputation: 63
I'm able to merge a multimdimensional array as CSV, but I have to fix the array keys for the headers. The merged array is naming the first value of the second array and adding an extra value that changes the order of the rest columns.
This is the array:
Array
(
[0] => Array
(
[key_1] => a
[key_2] => b
[key_3] => c
[key_4] => d
[key_5] => Array
(
[key_6] => a
[key_7] => b
[key_8] => d
[key_9] => z
)
)
)
This is the script:
<?php
$items = array();
$fp = fopen('filename.csv', 'w');
function array_keys_multi(array $items) {
$keys = array();
foreach ($items as $key => $value) {
$keys[] = $key;
if (is_array($items[$key])) {
$keys = array_merge($keys, array_keys_multi($items[$key]));
}
}
return $keys;
}
// I add the array keys as CSV headers
fputcsv($fp,array_keys_multi($items[0]));
foreach ($items as $file) {
$result = [];
array_walk_recursive($file, function($campo) use (&$result) {
$result[] = $campo;
});
fputcsv($fp, $result);
}
fclose($fp);
?>
The CSV output is adding an additional header called "key_5", instead of "key_6", which is the first of the next value of the second array that I need to follow.
key_1, key_2, key_3, key_4, key_5, key_6, key_7, key_8, key_9
a, b, c, d, a, b, d, z
I would like remove the "key_5" value as a header.
Upvotes: 0
Views: 62
Reputation: 6388
You can use array_walk_recursive
array_walk_recursive($a, function($v,$k) use (&$flat){
$flat[$k]=$v;
});
print_r($flat);
Working example :- https://3v4l.org/CaDdr
Upvotes: 0
Reputation: 57121
The problem is that you are always adding the key in, you can change it so that you only add it in if the element isn't a sub array in the inner most loop...
foreach ($items as $key => $value) {
if (is_array($items[$key])) {
$keys = array_merge($keys, array_keys_multi($items[$key]));
}
else {
$keys[] = $key;
}
}
Upvotes: 1