使用 json_encode (oop, php)

问题描述

我正在尝试创建待办事项列表。创建新帖子时,它应该将信息编码为 json 并将信息放入 json 数组中。但不知何故,似乎信息编码不正确,并且在尝试打印帖子时,我收到错误消息“为 foreach() 提供的参数无效”。我就是找不到错误在哪里。

我对此还很陌生,所以复杂的答案可能让我难以理解。

编辑: 添加整个该死的代码。有什么严重的错误。 ?‍♀️

索引:

    <?PHP 

spl_autoload_register(function ($class) {
    include $class . '.class.PHP';
});

$allPosts = new Lista;

if(isset($_REQUEST['addNewPost'])){
    $allPosts->addNewPost($_REQUEST['ett'],$_REQUEST['tva'],$_REQUEST['tre']);
}
?>

<?PHP $page_title = "Att göra lista";
include("includes/header.PHP");
?>
<?PHP
include("includes/sidebar.PHP");
?>
<h2>Min att göra lista</h2>


<form action="<?PHP echo $_SERVER['PHP_SELF'];?>" method="post">
Uppgift: <input type="text" name="ett"/><br/>
Utfarare: <input type="text" name="tva"/><br/>
Senast: <input type="text" name="tre"/><br/>
<input type="submit" name="addNewPost" value="Lägg till post"/>
</form>


<?PHP
  //Loopa igenom array
  foreach ($allPosts->getTheList() as $key=>$val) {
   echo "<section id='postPart'>" . $val->getEtt() . "<br/>" . $val->getTva(). " " . $val->getTre(). "</section><section id='buttonPart'><button type='button' name='klar'>Avklarad!</button> <button type='button' name='deletePost'>Ta bort</button>\n";
}

//echo "<section id='postPart'>" . $_REQUEST['one'] . "<br/>" . $_REQUEST['two'] . " " . $_REQUEST['three'] . "</section><section id='buttonPart'><button type='button' name='klar'>Avklarad!</button> <button type='button' name='deletePost'>Ta bort</button>\n";


var_dump($allPosts);
 
?>

</body>
</html>

班级:利斯塔:

 <?PHP
class Lista{
    public $theList=[];

        function __construct(){
            if(file_exists("text.json")>0)
                $this->theList = json_decode(file_get_contents('text.json'),true);
        }

        function addNewPost($ett,$tva,$tre){
            $posten = new Post ($ett,$tre);
            array_push ($this->theList,$posten);
            $jsonStr = json_encode($this->theList);
            file_put_contents("text.json",$jsonStr);
        }

        function getTheList( ){
            return $this->theList;
        }

}

班级帖子:

<?PHP
class Post{
    public $ett;
    public $tva;
    public $tre;

    function __construct ($ett,$tre){
        $this->ett = $ett;
        $this->tva = $tva;
        $this->tre = $tre;
    }

    function getEtt():string{
        return $this->ett;
    }

    function getTva(){
        return $this->tva;
    }

    function getTre(){
        return $this->tre;
    }
}

解决方法

我认为您的问题出在这一行:

$jsonStr = json_encode($this->$thePost,JSON_PRETTY_PRINT);

您可能正在尝试这样做:

$jsonStr = json_encode($thePost,JSON_PRETTY_PRINT);

因为 $thePost 是一个对象,而不是您的类的属性。如果 $thePost 是一个匹配属性名称的字符串,它就可以工作。

,

除了打字错误之外,要对对象数组进行 json_encode,您需要创建一个导出器方法,该方法返回每个属性的数组或实现 JsonSerializable

<?php
class Post implements JsonSerializable {
    protected $whatIs = ' ';
    protected $whoIs = ' ';
    protected $whenIs = ' ';
    
    function __construct($what,$who,$when){
        $this->whatIs=$what;
        $this->whoIs=$who;
        $this->whenIs=$when;
    }

    public function jsonSerialize()
    {
        return get_object_vars($this);
    }
}

$arr = [];

$arr[] = new Post(1,2,3);

echo json_encode($arr);

结果:

[{"whatIs":1,"whoIs":2,"whenIs":3}]