数组数据无法迭代(PHP)

Array Data Unable to be Iterated Through (PHP)

注意:这只是测试代码,因为我正在学习 PHP,所以没有实际意义。

基本上,我要问的是如何将对象数组转换回我可以使用的形式。

问题:我创建了一个包含 8 种不同农产品的新对象数组。我想将它们写入 .txt 文件,然后在编码后重新访问数组对象数据。目前,我收到“尝试获取非对象的 属性 'price'”的错误,我不确定为什么。

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} ]

Nvm,想通了。

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", json_encode($produceList)); //restart

$test = json_decode(file_get_contents("ProducePrice.txt"), true);


echo gettype($test);

foreach($test as $i){
  echo $i["name"];
};

发生这种情况是因为您试图从 Object 中调用一些东西 并且您的文件是文本而不是从中调用某些东西的对象。

$read = file("ProducePrice.txt"); // Not an Object Just array have a one Index

尝试

print_r($read); // To See Your Info More Readable to know what I mean