0

I'm trying to generate a list of articles from the this array

Array ( [0] => Array ( [id] => 1 [title] => Article1  ) [1] => Array ( [id] => 2 [title] => article2  ) )

Also add id value for each article, this is what I have tried, but its not working right.

    <ul>

<?php 

foreach ($result as $key => $value) {
    foreach ($value as $item) { ?>
    <li id=<?php echo "$id"; ?>> <?php echo "$item"; ?></li>
    <?php  
    }
}


?>  
    </ul>  

Your helps is highly appreciated.

2 Answers 2

4

You're close. $item is an associative array.You just need to access its values using the proper keys:

  <ul>

<?php 

foreach ($result as $key => $value) {
    foreach ($value as $item) { ?>
    <li id="<?php echo $item['id']; ?>"> <?php echo $item['value']; ?></li>
    <?php  
    }
}


?>  
    </ul>  
Sign up to request clarification or add additional context in comments.

5 Comments

I think $value is the associative array.
That's a numerical array containing the associative arrays.
No, that's $result. $key is 0 and 1 and $value is the associative array containing "id" and "title".
why to get $key, as not required/used here
@MMK In thi scase you would not need to get $key
1

Could you not just change the $key => $value in the first foreach so that it becomes:

<ul>
<?php foreach($result as $item){ ?>
<li id="<?php echo $item['id']; ?>>
<?php echo $item['title']; ?>
</li> 
<?php } ?>
</ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.