【发布时间】:2021-01-26 20:39:25
【问题描述】:
我正在尝试创建一个待办事项列表。创建新帖子时,它应该将信息编码为 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>
类:Lista:
<?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, $tva, $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, $tva, $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;
}
}
【问题讨论】:
-
请显示foreach,开启报错,
$this->$thePost错了 -
$thePost是一个对象,然后您将其用作$this->$thePost中的属性 -
@LawrenceCherone foreach 现在就在那儿。
-
@FelippeDuarte 我试图删除“this->”部分,但什么也没做。我从未使用过 php 类,所以我对现在的内容感到困惑。 ????
标签: php json class decode encode