【问题标题】:Error code "Invalid argument supplied for foreach()" when using json_encode (oop, php)使用 json_encode (oop, php) 时出现错误代码“foreach() 提供的参数无效”
【发布时间】: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-&gt;$thePost错了
  • $thePost 是一个对象,然后您将其用作$this-&gt;$thePost 中的属性
  • @LawrenceCherone foreach 现在就在那儿。
  • @FelippeDuarte 我试图删除“this->”部分,但什么也没做。我从未使用过 php 类,所以我对现在的内容感到困惑。 ????

标签: php json class decode encode


【解决方案1】:

除了错字之外,要 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}]

【讨论】:

  • 我不确定我是否实现了这个权利(所有代码都应该在“发布”类页面中吗?)但我已经能够删除错误代码,但仍然没有写在我的 .json 文件中。我根本没有收到任何错误代码,但没有回显,我的 .json 文件中也没有任何内容。我已经开始了三遍,但仍然无法正常工作。顺便说一句,哪里有错字?
  • 错字是@spzout 的答案。如果没有写入文件,那么您可能有权限问题,这将显示在错误日志中,在开发时始终启用错误报告。如果它正在写信给它,但你得到了[{},{},{}],那么它与我的回答有关。添加您的所有代码或共享一个 git 存储库,无法真正说出几个 sn-ps 的问题,例如您是否检查过表单正在发送值?
  • 还请注意,一旦您将类编码为 json 并保存到文件中,它就不会维护该类的方法/获取器,在回读时它只是一个数组,如果您想要所有您想要的应该使用serialise 而不是 json_encode
  • 代码正在发送值,现在已经开始(终于!)写入我的 .json 文件。虽然 foreach 循环仍然存在问题,但现在它说存在堆栈跟踪 #0 问题。我必须使用 json,因为任务是从 .json 文件中获取待办事项。这就是为什么我尝试使用不工作的 foreach 循环。
  • 正如所说的 getter 不存在,在 foreach 所在的位置执行 print_r($allPosts-&gt;getTheList()); 并且您看到它是一个普通数组,因此您不能执行 $val-&gt;getEtt(),而 $val['ett'] 应该可以工作跨度>
【解决方案2】:

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

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

您可能正在尝试这样做:

$jsonStr = json_encode($thePost, JSON_PRETTY_PRINT);

因为 $thePost 是一个对象,而不是你的类的属性。如果 $thePost 是与属性名称匹配的字符串,它可能会起作用。

【讨论】:

  • 数组中的对象呢?
  • 这没有任何区别,我已经能够删除错误代码,但我的 .json 中仍然没有写入任何内容或回显到屏幕上。就好像它在途中的某个地方停了下来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 2013-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多