【问题标题】:Array Data Unable to be Iterated Through (PHP)无法迭代的数组数据(PHP)
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这是因为你试图从 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-01
        • 2022-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多