【问题标题】:convert array into .txt file [duplicate]将数组转换为 .txt 文件 [重复]
【发布时间】:2011-04-27 21:36:17
【问题描述】:

可能重复:
Convert array into csv

嗨,

如何将数组转换成.txt文件?

这是我的数组:

Array
(
    [OrderList_RetrieveByContactResult] => Array
        (
            [OrderDetails] => Array
                (
                    [0] => Array
                        (
                            [entityId] => 156456
                            [orderId] => 110631
                            [orderName] => testing2
                            [statusTypeId] => 15656
                            [countryCode] => AU
                            [orderType] => 2
                            [invoiceNumber] => 1001
                            [invoiceDate] => 2010-10-19T00:00:00
                            [userID_AssignedTo] => 245454
                            [shippingAmount] => 8.95
                            [shippingTaxRate] => 0
                            [shippingAttention] => tttesst
                            [shippingInstructions] => this a test
                            [shippingOptionId] => 50161
                            [discountCodeId] => 0
                            [discountRate] => 0
                            [totalOrderAmount] => 143.8
                            [directDebitTypeId] => 0
                            [directDebitDays] => 0
                            [isRecur] => 
                            [nextInvoiceDate] => 0001-01-01T00:00:00
                            [endRecurDate] => 0001-01-01T00:00:00
                            [cycleTypeID] => 1
                            [createDate] => 2010-10-19T05:40:00
                            [lastUpdateDate] => 2010-10-19T05:40:00
                            [deleted] => 
                            [products] => Array
                                (
                                    [Product] => Array
                                        (
                                            [productId] => 455
                                            [productCode] => 
                                            [productDescription] => testtest
                                            [units] => 3
                                            [unitPrice] => 44.95
                                            [unitTaxRate] => 0
                                            [totalProductPrice] => 134.85
                                            [productName] => Skin Support Tablets
                                        )
                                )

                            [addresses] => Array
                                (
                                    [Address] => Array
                                        (
                                            [addressTypeID] => 8
                                            [addressLine1] => Cebu
                                            [city] => City
                                            [zipcode] => 6000
                                            [state] => cebu
                                            [countryCode] => PH
                                        )
                                )

                        )

                    [1] => Array
                        (
                            [entityId] => 315456
                            [orderId] => 321321
                            [orderName] => testing
                            [statusTypeId] => 3213
                            [countryCode] => AU
                            [orderType] => 2
                            [invoiceNumber] => 1002
                            [invoiceDate] => 2010-10-19T00:00:00
                            [userID_AssignedTo] => 11711
                            [shippingAmount] => 8.95
                            [shippingTaxRate] => 0
                            [shippingAttention] => 
                            [shippingInstructions] => 
                            [shippingOptionId] => 50161
                            [discountCodeId] => 0
                            [discountRate] => 0
                            [totalOrderAmount] => 408.45
                            [directDebitTypeId] => 0
                            [directDebitDays] => 0
                            [isRecur] => 
                            [nextInvoiceDate] => 0001-01-01T00:00:00
                            [endRecurDate] => 0001-01-01T00:00:00
                            [cycleTypeID] => 1
                            [createDate] => 2010-10-08T18:40:00
                            [lastUpdateDate] => 2010-10-19T18:36:00
                            [deleted] => 
                            [products] => Array
                                (
                                    [Product] => Array
                                        (
                                            [productId] => 11564
                                            [productCode] => 
                                            [productDescription] => 
                                            [units] => 10
                                            [unitPrice] => 39.95
                                            [unitTaxRate] => 0
                                            [totalProductPrice] => 399.5
                                            [productName] => Acne Clearing Gel
                                        )

                                )

                            [addresses] => Array
                                (
                                    [Address] => Array
                                        (
                                            [addressTypeID] => 8
                                            [addressLine1] => Cebu City
                                            [city] => Cebu
                                            [zipcode] => 6000
                                            [state] => 
                                            [countryCode] => PH
                                        )

                                )

                        )

                )

        )

)

【问题讨论】:

  • 你的问题毫无意义。 .txt 文件没有结构。
  • 你能显示你的 .txt 输出吗?
  • file_puts_contents('file.txt', print_r($array, true));
  • 您在问题中显示的内容不是文本文件吗?
  • @rayss:结构没有那么复杂。

标签: php arrays file format text-files


【解决方案1】:

如果你希望它是可解析的,你可以使用

  • var_export — 输出或返回变量的可解析字符串表示

示例

file_put_contents('array.txt', var_export($array, TRUE));

如果您希望它看起来像您的问题,请将TRUE 作为第二个参数传递给print_r

file_put_contents('array.txt', print_r($array, TRUE));

EDIT 您在 cmets 中提到您希望将数组转换为 CSV 文件。这更难。您的数组是嵌套的,而 CSV 文件基本上是一个暗淡的数组,例如

array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => 'vn');

相当于一个 CSV 文件,其中第一行是数组键,第二行是值。

k1; k2; ...; kn
v1; v2; ...; vn

单个 dims 数组通常在另一个数组中,所以你有一个这样的集合:

array(
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => 'vn'),
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => 'vn')
);

在这里,您必须先获取键,然后仅从数组中获取后续行的值,例如

k1; k2; ...; kn
v1; v2; ...; vn
v1; v2; ...; vn

问题是,您的数组嵌套得更深。你会把 address 数组放在哪里?唯一可行的方法是遍历数组并仅获取那些包含标量类型的键和值并对任何嵌套数组进行线性化,例如

array(
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => array( 'skn' => 'svn' ) ),
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => array( 'skn' => 'svn' ) ),
);

必须变成

k1; k2; ...; skn
v1; v2; ...; svn
v1; v2; ...; svn

如果不清楚,这里有一个说明:

幸运的是,这可以通过迭代器来实现:

$orderDetails = $array['OrderList_RetrieveByContactResult']['OrderDetails'];
foreach( $orderDetails as $key => $details ) {

    $iterator = new RecursiveIteratorIterator(
            new RecursiveArrayIterator($details));

    if($key === 0) {
        $keys = array();
        foreach($iterator as $k => $v) {
            $keys[] = $k;
        }
        echo implode(';', $keys);
    }

    $values = array();
    foreach($iterator as $val) {
        $values[] = $val;
    }
    echo PHP_EOL, implode(';', $values);
}

上面的代码应该输出描述的格式。示例见http://www.ideone.com/I70dD

要将其写入文件,您可以将其组合成一个字符串变量,然后file_put_contents 一次将其全部写入,或者使用文件指针逐行写入。如果你不使用implode 而是遍历$flattened 数组,你也可以使用fputcsv

【讨论】:

  • 您肯定不想将 true 作为 var_export 中的第二个参数传递,因为这会将其导出到变量而不是输出内容?
  • @Alex 我想将其传递给file_put_contents,以便将其写入文件。为此,我必须使用TRUE
  • 感谢您的帖子,它对我有很大帮助,但您的代码有一点问题。似乎 [countryCode] => AU 没有出现,而是将替换产品数组中的 [countryCode] => PH。这是我得到的:156456;110631;testing2;15656;PH;2;.... 等 315456;321321;testing;3213;PH;2.... 等
  • @rayss 这是因为iterator_to_array 将它首先在内存中返回的数组组装起来,并且来自嵌套级别的键将覆盖更高级别的同名键。我已经更新了代码。现在它不应该再这样做了。如果您想更好地控制迭代,您可能还想看看stackoverflow.com/questions/2207599/…
  • 非常感谢它确实有效。谢谢您的帮助。我从你身上学到了很多:)
【解决方案2】:

如果您想将变量保存在文本文件中,您可以使用 serialize() / unserialize() 函数:

$data = array(1, 2, 3, '');
$toBeSaved = serialize($data);
file_put_contents('somefile.txt', $toBeSaved);

然后恢复它...

$toBeRestored = file_get_contents('somefile.txt');
$data = unserialize($toBeRestored);

【讨论】:

    【解决方案3】:

    也许你想要的是fputcsv

    【讨论】:

    • 结构没有那么复杂。
    • 那你想要什么结构?
    猜你喜欢
    • 1970-01-01
    • 2017-04-14
    • 2021-06-19
    • 2017-05-07
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2021-03-30
    相关资源
    最近更新 更多