Reputation:
I have JSON https://jsonplaceholder.typicode.com/todos/ and i need to put all data in table. How can i access the "completed" ? I think that is bool. I need one button that print only TRUE and another one that print only FALSE. i tried something like this but doesn't work.
This is what i tried : PHP code
<?php } elseif (isset($_POST['onlyCompBtn'])) {?>
<?php $data = $_POST['onlyCompBtn']; ?>
<br></br>
<table class="table table-striped">
<tr>
<th>User ID:</th>
<th>ID:</th>
<th>Title:</th>
<th>Compiled:</th>
</tr>
<?php foreach ($arrays as $key => $value) { ?>
<tr>
<td> </td>
<td> </td>
<td></td>
<td><?php echo $value -> completed['1'] ?></td> // ['1'] or ['true'] doesn't work
</tr>
</table>
<?php }?>
<?php } ?>
I get this error : "Trying to access array offset on value of type bool"
Any suggestions? TIA!
Upvotes: 0
Views: 117
Reputation:
This gonna work :
<?php foreach ($arrays as $key => $value) { ?>
<tr>
<td><?php echo $value->userId ?> </td>
<td><?php echo $value->id ?> </td>
<td><?php echo $value->title ?> </td>
<td><?php echo $value->completed ? 'Compiled' : 'Not Compiled' ?></td>
</tr>
<?php } ?>
Upvotes: 0
Reputation: 18002
If you look at your json completed
is just a boolean, not an array
({"userId": 1, "id": 1, "title": "delectus aut autem","completed": false }...
).
Change:
<td><?php echo $value -> completed['1'] ?></td>
To:
<td><?php echo ($value->completed ? 'TRUE' : 'FALSE') ?></td>
Udate
If you want to filter the results you can place if conditions inside the foreach, let's say you want to show only the completed titles:
<?php foreach ($arrays as $key => $value) {
if ($value->completed) {
?><tr>
<td><?php echo $value->userId ?></td>
<td><?php echo $value->id ?></td>
<td><?php echo $value->title ?></td>
<td><?php echo ($value->completed ? 'TRUE' : 'FALSE') ?></td>
</tr><?php
}
}
?></table>
In this case that you only show the completed ones it might not make sense to print it's completed column and it's value as it would be always 'TRUE' but I leave it just in case your filters are different.
Notice that the </table>
should be placed outside the foreach.
Upvotes: 1
Reputation: 48
Try decoding the data first with json_decode($arrays) after you've set the variable, I believe this is your problem
Upvotes: 0