I want to display skills and image from JSON using PHP I’m trying to research but not working
Error Message:
Notice: Array to string conversion in C:xampphtdocstestview.php on line 27
Notice: Array to string conversion in C:xampphtdocstestview.php on line 32
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 (Output)
2
Answers
Answer:
because your
$user['image']
is not string, that one is array.try print your
$user['image']
and you will know.ps: use foreach instead your array.