Home > Software design >  Array Data Unable to be Iterated Through (PHP)
Array Data Unable to be Iterated Through (PHP)

Time:09-25

NOTE: This is just test code because I am learning PHP, so there's no real point to it.

Essentially, all I'm asking is how to turn the array of objects back into a form that I can use.

ISSUE: I've created a new object array with 8 different produce items. I would like to write them to a .txt file and then re-access the array objects data after they have been encoded. Currently, I am getting an error of "Trying to get property 'price' of non-object," and I'm not sure why.

<?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
};

?>

This is what ProducePrice.txt looks like:

[ {"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} ]

CodePudding user response:

Nvm, figured it out.

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

CodePudding user response:

That's happen because you are try to call some thing from Object and Your file is text not an object to call some thing from it.

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

try

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