Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following array. For simplicity, i have only posted one item but it's a big array that contains a huge number of keys and values

Array
(
[Maths] => Array
    (
        [00] => 0
        [01] => 0
        [02] => 0
        [03] => 0
        [04] => 0
        [05] => 0
        [06] => 0
        [07] => 0
        [08] => 0
        [09] => 0
        [10] => 0
        [11] => 0
        [12] => 0
        [13] => 0
        [14] => 0
        [15] => 0
        [16] => 0
        [17] => 9
        [18] => 5128
        [19] => 5763
        [20] => 1734
        [21] => 632
        [22] => 299
        [23] => 190
    )

I would like to put the contents of the array into a csv file which will be structured like this. One line per outer array and conctenate the values of the inner array to it.

So the above array will appear like this. Please bear in mind that it's not a static array. All the information in the array is dynamic

Math,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,5128,5763,1734,632,299,190

Please help

share|improve this question

2 Answers 2

up vote 1 down vote accepted
$data=Array(...);
$csv="";
foreach ($data as $key => $value) {
    $csv.=$key.",".implode(",", $value)."\n";
}
share|improve this answer

if your structure is something like:

array ( key1 => array(), key2 => array() ... ) you could do this:

$csvOutput = "";

foreach ($baseAy as $key => $subAy) {

    $csvOutput.= "\n".$key.",";

    foreach ($subAy as $value) {
         $csvOutput.= $value.",";
    }
}

print_r($csvOutput);
share|improve this answer
1  
above code gives comma(,) at the end, instead of inner foreach, you can use implode with comma(,) and concatenate. –  codepiper Jan 14 '14 at 9:34
    
@codepiper you are right, it is a better solution ;) –  Luca Iaco Jan 14 '14 at 9:38
    
thanks, it works fine –  user3172841 Jan 16 '14 at 14:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.