将多维数组保存到txt

时间:2014-05-29 11:42:43

标签: php multidimensional-array

您好我有一个存储产品的阵列。以下是第一个产品的示例:

$_SESSION['pricebook']['product1'] = array(
'name' => 'product1',
'description'=>'Board my Cat(s)!',
'price'=>25.95,
);

我有一个购物车阵列,用于存储用户从价格手册数组中选择的每个产品。

if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}

如何将购物车写入orders.txt文件?我尝试过的所有内容都给了我“阵列通知:数组到字符串转换”错误。

注意:产品已添加到购物车中:

if (isset($_GET["product1"]) && $_GET["product1"]=="Add") {
$pid = $_GET["name"];   
if (!isset($_SESSION['cart'][ $pid ])) { $_SESSION['cart'][ $pid ]; }
array_push($_SESSION['cart'][ $pid ]);
} 

还有什么方法可以将它保存为人类可读格式的txt文件,如收据?

3 个答案:

答案 0 :(得分:0)

你可以尝试:

$handle = fopen('orders.txt', 'w+'); // change this based on how you would like to update the file
fwrite($handle, print_r($_SESSION['cart']), true);
fclose($handle);

答案 1 :(得分:0)

您可以使用PHP serialize()进行此操作。

  

生成值的可存储表示。

     

这对于存储或传递PHP值非常有用,而不会丢失其类型和结构。

     

要再次将序列化字符串转换为PHP值,请使用unserialize()

要保存,您的代码可能如下所示

$representation = serialize($_SESSION['cart']);
// save $representation to your txt file/whatever

并加载值,只需按照手册中的说明进行操作

// load data into $representation 
$_SESSION['cart'] = unserialize($representation);

如果您想要更漂亮的格式,可以使用json_encode()设置JSON_PRETTY_PRINT标记

$representation = json_encode($_SESSION['cart'], JSON_PRETTY_PRINT);
// save $representation to your txt file/whatever

// load data into $representation 
$_SESSION['cart'] = json_decode($representation);

答案 2 :(得分:0)

使用serializejson_encode

你可以像这样使用serialize()

$t = serialize($_SESSION['cart']);
file_put_contents('filename.txt', $t);

或者json_encode()

$t = json_encode($_SESSION['cart']);
file_put_contents('filename.txt', $t);

serialize可以稍微快一点,但是特定于PHP,而json_encode会生成一个JSON字符串,可以输入任何东西,包括烤面包机:D JSON字符串也会留下一个比序列化的足迹更小。

相关问题