【发布时间】:2021-11-18 04:55:00
【问题描述】:
注意:这只是测试代码,因为我正在学习 PHP,所以没有真正的意义。
基本上,我要问的只是如何将对象数组转换回我可以使用的形式。
问题:我创建了一个包含 8 种不同农产品的新对象数组。我想将它们写入 .txt 文件,然后在编码后重新访问数组对象数据。目前,我收到“尝试获取非对象的属性‘价格’”的错误,我不知道为什么。
<?php
class Item{
public $name;
public $price;
function __construct( $name, $price ){
$this->name = $name;
$this->price = $price;
}
};
$produceList = [
new Item("bananas", 0.59),
new Item("grapes", 2.99),
new Item("apples", 1.49),
new Item("pears", 1.39),
new Item("lettuce", 0.99),
new Item("onions", 0.79),
new Item("potatoes", 0.59),
new Item("peaches", 1.59)
];
file_put_contents("ProducePrice.txt", ""); //clear file for testing
$file = fopen("ProducePrice.txt", "a");
fwrite($file, json_encode($produceList));
fclose($file);
$read = file("ProducePrice.txt");
foreach($read as $i){
echo $i->price; //error: Trying to get property 'price' of non-object
};
?>
这是 ProducePrice.txt 的样子:
[ {"name":"bananas","price":0.59},{"name":"grapes","price":2.99},{"name":"apples","price":1.49},{"name":"pears","price":1.39},{"name":"lettuce","price":0.99},{"name":"onions","price":0.79},{"name":"potatoes","price":0.59},{"name":"peaches","price":1.59} ]
【问题讨论】:
标签: php arrays decode encode write