读取数组并写入txt文件

时间:2013-08-04 03:27:14

标签: php arrays file

我有一个这样的数组:

Array
(
    [0] => Array
       (
        [name] => post
        [fql_result_set] => Array
            (
                [0] => Array
                    (
                        [post_id] => value
                        [message] => value
                    )

                [1] => Array
                    (
                        [post_id] => value
                        [message] => value
                    )

       )
)

我想将数组写入文件,例如:

post_id = value;
message = value;

-----

post_id = value;
message = value;

我知道写作我可以使用:

    file_put_contents('file.txt', print_r($array[0], true));

但我需要做一个“解析”...我该怎么做? 有谁可以帮助我吗? 抱歉我的英文不好:(

1 个答案:

答案 0 :(得分:0)

您可以使用for

<?php
$result = $data[0]['fql_result_set'];
$total = count($result);
for ($i=0; $i < $total; $i++)
{
    echo "post_id = ", $result[$i]['post_id'], "\n";
    echo "message = ", $result[$i]['message'], "\n";
    echo "------------------------\n";
}

foreach

$result = $data[0]['fql_result_set'];
foreach ($result as $outer)
{
    foreach ($outer as $key => $value)
    {
        echo $key, " = ", $value, "\n";
    }
    echo "------------------------\n";
}

<强> Live DEMO.

通过将其附加到结尾来保存到文件:

$file = 'file.txt';
$result = $data[0]['fql_result_set'];
foreach ($result as $outer)
{
    foreach ($outer as $key => $value)
    {
        file_put_contents($file, "{$key} = {$value}\r\n", FILE_APPEND | LOCK_EX);
    }
    file_put_contents($file, "----\r\n", FILE_APPEND | LOCK_EX);
}

Append to the end of the file using FILE_APPEND and LOCK_EX flag to prevent anyone from accessing the file until we're done writing.