简体   繁体   中英

I have problem with accessing this array PHP

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!

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.

设置变量后,首先尝试使用 json_decode($arrays) 解码数据,我相信这是你的问题

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 }   ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM