在HTML中将数组转换为列表时遇到问题

时间:2016-10-09 03:53:28

标签: php html arrays

我一直试图找出我收到错误的原因

为foreach()提供的参数无效

在我的HTML文件的第20行,我无法弄清楚我已经从HTML文件独立运行我的PHP代码,PHP代码按预期返回我的对象​​。一旦我尝试在我的HTML文件中调用它来显示它就不起作用这里都是我的文件

PHP:     

require 'practice.view.php';

 class Task {

  public $description;

  public $completed = false;

  public function __construct($description){

    $this->description = $description;
  }

  public function complete(){

    $this->completed = true;
  }

  public function iscomplete(){

    return $this->completed;
  }
}




$tasks = [
  new Task('Go to the market'),

  new Task('eat a marshmellow'),

  new Task('Join a soccer league')
];



die(var_dump($tasks));

HTML:

<!doctype html>

<html lang="en">

<head>

<!meta charset="utf-8"->

  <title>Practice</title>

</head>

<body>

  <h1>Tasks List </h1>
    <ul>
      <?php foreach ($tasks as $task) : ?>

          <li>
            <?= $task->description; ?>
          </li>

      <?php endforeach; ?>
   </ul>
</body>
</html>

感谢您提前获取任何帮助

2 个答案:

答案 0 :(得分:0)

filename.php,

<?php

  class Task {

  public $description;

  public $completed = false;

  public function __construct($description){

    $this->description = $description;
   }

  public function complete(){

    $this->completed = true;
  }

  public function iscomplete(){

    return $this->completed;
  }
}




$tasks = [
  new Task('Go to the market'),

  new Task('eat a marshmellow'),

  new Task('Join a soccer league')
];

?>

HTML,

<!doctype html>

<html lang="en">

<head>

<!meta charset="utf-8"->

  <title>Practice</title>

</head>

<body>

<?php require 'filename.php'; ?>

  <h1>Tasks List </h1>
    <ul>
      <?php foreach ($tasks as $task) : ?>

          <li>
            <?= $task->description; ?>
          </li>

      <?php endforeach; ?>
    </ul>
</body>
</html

您应该使用require'filename.php'将您的课程包含在您的html文件中;你正在这样做,你将html包含在类文件中。

答案 1 :(得分:0)

我的问题的答案只是放置我的“require ...”语句,在这种情况下,它位于我的代码的顶部,当它应该位于PHP文件中我的代码的底部时。感谢所有试图回答这个问题的人

 class Task {

  public $description;

  public $completed = false;

  public function __construct($description){

    $this->description = $description;
  }

  public function complete(){

    $this->completed = true;
  }

  public function iscomplete(){

    return $this->completed;
  }
}




$tasks = [
  new Task('Go to the market'),

  new Task('eat a marshmellow'),

  new Task('Join a soccer league')
];



die(var_dump($tasks));

require 'practice.view.php';