如何使用php循环或显示json数据?

问题描述 投票:-1回答:1

我想使用我想研究但不能正常工作的PHP从JSON显示技能和图像

错误消息:

注意:第27行,C:\ xampp \ htdocs \ test \ view.php中的数组到字符串的转换

注意:第32行中C:\ xampp \ htdocs \ test \ view.php中的数组到字符串的转换

data.json

{
    "UserData": [

    {
        "id": "name",
        "fname": "Joey",
        "lname": "Tulang",
        "age": "29",
        "gender": "Male",
        "skills": [ "HTML", "CSS", "JavaScript" ],
        "image": [ "html.jpg", "css.jpg", "js.jpg" ]
    },
    {
        "id": "2",
        "fname": "Angelica",
        "lname": "Balce",
        "age": "20",
        "gender": "Female",
        "skills": [ "C++", "Python", "PHP"],
        "image": [ "c++.jpg", "python.jpg", "php.jpg" ]
    },
    {
        "id": "3",
        "fname": "Mj",
        "lname": "King",
        "age": "21",
        "gender": "male",
        "skills": [ "Photoshop", "Figma", "Corel Draw"],
        "image": [ "photoshop.jpg", "figma.jpg", "cdraw.jpg" ]
    }       

    ]   
}

index.php

<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
</head>
<body>

<?php

$jsondata = file_get_contents("data.json");
$json = json_decode($jsondata, true);
$output = "<ul>";

foreach ( $json['UserData'] as $display ) {
  $output .="<li>" .$display['fname']. " <a href='view.php?id=".$display['id']."'>View User Data</a></li> </br>";
}

$output .= "</ul>";

echo $output;

?>

</body>
</html>

view.php

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

$key = array_search((int) $_GET['id'], array_column($json['UserData'], 'id'));

// if $key false, was not found, presume it was...

$user = $json['UserData'][$key];
?>
<!DOCTYPE html>
<html>
<head>
    <title>View User Data</title>
</head>
<body>

    <!-- Display User Data Here -->

    <p>First Name: <?= $user['fname'] ?></p>
    <p>Last Name: <?= $user['lname'] ?></p>
    <p>Age: <?= $user['age'] ?></p>
    <p>Gender: <?= $user['gender'] ?></p>

    <p>Skills</p>
    <ul>
        <?= "<li>" .$user['skills']. "</li>" ?>
    </ul>

    <p>Image</p>

        <?= "<imge src='image/" .$user['image']. "'/>" ?>


</body>
</html>

view.php(输出

https://ibb.co/fk4LPLG

php arrays json loops
1个回答
0
投票

因为您的$user['image']不是字符串,所以那个是数组。尝试打印您的$user['image'],您会知道的。

ps:使用foreach代替您的数组。

© www.soinside.com 2019 - 2024. All rights reserved.