Reputation: 2728
I'm trying to write multiple values into a single csv cell using PHP loops and arrays.
<?php
$data = array
(
3 => array
(
'name' => 'Mars',
'type' => 'Terrestrial Planet',
'diameter' => 0.532,
'mass' => 0.11,
'rings' => 0,
'position' => 4,
'gases' => array
(
0 => 'CO2',
1 => 'N2',
2 => 'Ar'
),
'satellites' => array
(
0 => array
(
'name' => 'Phobos',
'radius' => 6.20
),
1 => array
(
'name' => 'Deimos',
'radius' => 6.20
)
)
)
);
function writeCSV($array){
$str = [];
$fp = fopen('file.csv', 'w');
fputcsv($fp, array('Name','Type','Diameter','Mass','Rings','Position','Gases','Satellite-Name','Satellite-Radius'),"\t");
foreach ($array as &$fields) {
$str[] = $fields['name'];
$str[] = $fields['type'];
$str[] = $fields['diameter'];
$str[] = $fields['mass'];
$str[] = $fields['rings'];
$str[] = $fields['position'];
if(is_array($fields['gases'])){
foreach ($fields['gases'] as $gas)
array_push($str, $gas);
}
if(is_array($fields['satellites'])){
foreach ($fields['satellites'] as $satellite)
$str[] = $satellite['name'];
foreach ($fields['satellites'] as $satellite)
$str[] = $satellite['radius'];
}
fputcsv($fp, $str);
$str = [];
}
}
writeCSV($data);
?>
The outcome of this writes:
Name Type Diameter Mass Rings Position Gases Satellite-Name Satellite-Radius
Mercury,"Terrestrial Planet",0.382,0.06,0,1
Venus,"Terrestrial Planet",0.949,0.82,0,2,CO2,N2
Earth,"Terrestrial Planet",1,1,0,3,N2,O2,Ar,Moon,1737.1
Mars,"Terrestrial Planet",0.532,0.11,0,4,CO2,N2,Ar,Phobos,Deimos,6.2,6.2
to the file. I really need it to write multiple (Gases, Satellite-Name Satellite-Radius) values into a single cell seperated by a space and wrapped in quotes say, i.e.
Name Type Diameter Mass Rings Position Gases Satellite-Name Satellite-Radius
Mercury,"Terrestrial Planet",0.382,0.06,0,1
Venus,"Terrestrial Planet",0.949,0.82,0,2,"CO2 N2"
Earth,"Terrestrial Planet",1,1,0,3,"N2 O2 Ar",Moon,1737.1
Mars,"Terrestrial Planet",0.532,0.11,0,4,"CO2 N2 Ar","Phobos Deimos","6.2 6.2"
I guess this would occur by intercepting the satellites and gases loops somehow but am struggling to concatenate or augment the gases and satellite loops to get the data into one array cell value.
Upvotes: 0
Views: 961
Reputation: 96159
The gases are easy, instead of
foreach ($fields['gases'] as $gas)
array_push($str, $gas);
use
$str[] = join(' ', $fields['gases']);
For the names and radii the simplest solution is probably array_column, as long as (PHP 5 >= 5.5.0)
isn't a problem....
$str[] = join(' ', array_column($fields['satellites'], 'name'));
$str[] = join(' ', array_column($fields['satellites'], 'radius'));
but if any of these values may contain whitespaces (e.g. Jupiter's moon S/2000 J 11
) you have to encode that first.
Upvotes: 1