-1

I got some JSON and i need to encode it. The encoding works fine. This is my JSON:


{
   "5daeff6f4090e": {
       "title":"I'm cute",
       "photo":"adorable-animal-bed-2061057.jpg"
   },
   "5daeffw3g454":{
       "title":"No, I'm the cutest",
       "photo":"animal-chihuahua-cute-39317.jpg"
   }
}

But when i'm inserting the data into a foreach-loop i can't figure out how to get the property-name. This property-name is being used for the url. I can call the title and photo.

This is my PHP-code:

<?php 
    // decode json
    $json_url = file_get_contents('./data/articles.json');
    $json = json_decode($json_url);
?>
    <div class="articles">
    <?php foreach($json as $item){?>
        <!-- get every cards data -->
        <a href="detail.php?=<?php echo $item;?>" class="article-item">
            <img src="images/<?php echo $item->photo;?>">
            <h3><?php echo $item->title;?></h3>
        </a>
    <?php };?>

Can someone help me?

jensderyckere
  • 51
  • 1
  • 5

1 Answers1

0

Take a look at the documentation and you'll understand.

https://www.php.net/manual/en/control-structures.foreach.php

<?php 

    // decode json
    $json_url = file_get_contents('./data/articles.json');
    $json = json_decode($json_url);
?>
    <div class="articles">
    <?php foreach($json as $key => $item){?>
        <!-- get every cards data -->
        <a href="detail.php?=<?php echo $key;?>" class="article-item">
            <img src="images/<?php echo $item->photo;?>">
            <h3><?php echo $item->title;?></h3>
        </a>
    <?php };?>
Fred
  • 868
  • 10
  • 22