如何循环PHP PDO FETCH ALL ASSOC ARRAY?

时间:2014-12-21 04:32:48

标签: php mysql arrays pdo

My Array O / P格式:

 Array
    (
        [0] => Array
            (
                [activity_id] => 2
                [ip_address] => 127.0.0.1
                [activity_name] => B
                [start_date] => 2014-12-03
                [end_date] => 2014-12-31
                [task_manager] => fd
            )

    [1] => Array
        (
            [activity_id] => 3
            [ip_address] => 127.0.0.1
            [activity_name] => dsw
            [start_date] => 12/04/2014
            [end_date] => 12/05/2014
            [task_manager] => Hello_am
        )

    [2] => Array
        (
            [activity_id] => 4
            [ip_address] => 127.0.0.1
            [activity_name] => dswfwaesf
            [start_date] => 12/04/2014
            [end_date] => 12/05/2014
            [task_manager] => Hello_am_2
        )

)

如何遍历数组,以便在csv文件中获取所有列名称的值?到目前为止,我已经尝试过这样做:

$chart_init= new ManageActivity;
$fp=fopen($filename,"w");
$list_chart=$chart_init->listActivityProject();
$separator="";
$comma="";
print_r($list_chart);

foreach($list_chart as $name=>$value)
    {
        $separator.=$comma . '' .str_replace('','""',$name);
        $comma=",";

    }
$separator.="\n";
fputs($fp,$separator);

echo 'true';
fclose($fp);

这只给我0,1,2作为答案。不知怎的,我无法根据列名获取行。请不要理解任何帮助。

1 个答案:

答案 0 :(得分:1)

可能的解决方案之一可能如下:

<?php

$list = array (
    array('activity_id' => '2',
          'ip_address' => '127.0.0.1',
          'activity_name' => 'B',
          'start_date' => '2014-12-03',
          'end_date' => '2014-12-31',
          'task_manager' => 'fd'),
    array('activity_id' => '3',
          'ip_address' => '127.0.0.1',
          'activity_name' => 'dsw',
          'start_date' => '12/04/2014',
          'end_date' => '12/05/2014',
          'task_manager' => 'Hello_am'),
    array('activity_id' => '4',
          'ip_address' => '127.0.0.1',
          'activity_name' => 'dswfwaesf',
          'start_date' => '12/04/2014',
          'end_date' => '12/05/2014',
          'task_manager' => 'Hello_am_2')
);


$headers = array('activity_id','ip_address','activity_name','start_date','end_date','task_manager');

$fcsv = fopen('file.csv', 'w');

fputcsv($fcsv, $headers);

foreach ($list as $row) {
    fputcsv($fcsv, $row);
}

fclose($fcsv);
?>

希望它有用!