PHP,使用类寻址对象

时间:2019-03-10 15:13:30

标签: php json class object instantiation

我正在尝试使用类将json数据库中的所有名称列出为html。 html输出应如下所示:-

  

字符

     
      
  • 姓名:John
  •   
  • 名称:Sarah
  •   
  • 名称:Michael
  •   

我已经设法用我的代码达到了这一目标。我知道这段代码还没有完成或有错误,但是我仍然是一个初学者并正在学习。您能帮我使此代码生效吗?

Json数据库文件

  

databas.json

{
"results": [
    {
        "name": "John",
        "height": "182 cm",
        "mass": "80 kg",
    },
    {
        "name": "Sarah",
        "height": "165 kg",
        "mass": "60 cm",
    },
    {
        "name": "Michael",
        "height": "178 cm",
        "mass": "75 kg",
    },
    ]
}

索引文件

  

index.php

<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">

        <title>Character</title>

    </head>

    <body style="margin-bottom:20em;">
        <h1>Characters</h1>
            <?php include('characters.php'); ?>

            <?php 
            $data = file_get_contents("databas.json");
            $data = json_decode($data, true);

            echo '<pre>';
            print_r($data);
            echo '</pre>';

            ?>
    </body>
</html>

类代码

  

characters.php

<?php

class Character {

        private $name;

public function __construct($name) {
            $this->name = $name;

        }
public function getName($name){
        return $this->name;
        }

}
 ?>
  

$ data的内容是

Array
(
    [results] => Array
        (
            [0] => Array
                (
                    [name] => John
                    [height] => 182 cm
                    [mass] => 80 kg
                )

            [1] => Array
                (
                    [name] => Sarah
                    [height] => 165 kg
                    [mass] => 60 cm
                )

            [2] => Array
                (
                    [name] => Michael
                    [height] => 178 cm
                    [mass] => 75 kg
                )

        )

)

1 个答案:

答案 0 :(得分:0)

我不确定我是否能使您满意,但是您可以执行简单的foreach循环:

$data = file_get_contents("databas.json");
$data = json_decode($data, true);

foreach($data["result"] as $e) {
    echo "Name: " . $e["name"];
}

true中发送json_decode的通知将返回关联数组,因此您可以使用[key]访问名称键,因此在include('characters.php');中不需要

编辑:如果要使用该类:

foreach($data["result"] as $e) {
    $character = new Character($e["name"]);
    $characters[] = $character;
}

foreach($characters as $character) {
    echo "Name: " . $character->getName();
}