将php关联数组写入文本文件

时间:2014-12-04 05:05:58

标签: php mysql fwrite

我想写一个mysql_fetch_assoc(返回一个关联数组)值到文本文件, 虽然我想以下面的方式得到输出

ID => 17
CODE => 4
Value => 59559

它只是打印如下

17
4
59595
25
0

所以这是我目前用于获取结果的代码,任何人都可以帮助我

$query = "CALL pro_details($ID, '$start', '$end', $limit, $pos);";
        $result = mysql_query($query, $con);
        $myFile = "debug.txt";
        $fh = fopen($myFile, 'w') or die("can't open file");
        while($stringData_2 = mysql_fetch_assoc($result)){
                foreach ($stringData_2 as $string) {
                    fwrite($fh, $string);
                    $stringbreak = "\n";
                    fwrite($fh, $stringbreak);
                }
                $stringbreak = "----------------\n";
                fwrite($fh, $stringbreak);
        }
        fclose($fh);

5 个答案:

答案 0 :(得分:4)

将您的fwrite()来电更改为:

foreach ($stringData_2 as $key=>$string) {
    fwrite($fh, $key ." => ".$string);
    $stringbreak = "\n";
    fwrite($fh, $stringbreak);
}

答案 1 :(得分:3)

如何尝试

foreach ($stringData_2 as $index => $string) {
    fwrite($fh, $index.'=>'.$string);
    $stringbreak = "\n";
    fwrite($fh, $stringbreak);
}

答案 2 :(得分:1)

    while($stringData_2 = mysql_fetch_assoc($result)){
               array_walk( $stringData_2 'displayData');


        }

...

function displayData($item, $key)
{
     fwrite($fh, "$key." => " . $item . "\n");
}

答案 3 :(得分:1)

在foreach循环中,您可以同时获得数组的键和值

foreach($variable as $key => $value) {
    // so that u can print both the keys and values
    $key ---> ID,code,Value
    $value ---> 12,4,59559
}

http://php.net/manual/en/control-structures.foreach.php

答案 4 :(得分:1)

你可以这样解决

while($stringData_2 = mysqli_fetch_assoc($result)){
    foreach ($stringData_2 as $key=>$string) {
         fwrite($fh, $key.'=>'.$string);
         $stringbreak = "\n";fwrite($fh, $stringbreak);
    }
   $stringbreak = "----------------\n";
   fwrite($fh, $stringbreak);
}