0

I get the result from my database i this type of array format.Now i want to print the question,answer and category name from the array what I do?

<?php  $v1 = '';
    foreach($var as $data){ 

 ?> 
<div class="faqHeader"> <?php echo $data['category_name'];?> </div>             
    <div class="panel-group" id="<?php echo $data->title;?>">

I tried these cod but not get the answer.In $var i get the all the array value

enter image description here

2
  • you are missing } of foreach loop. and what is title ? Try $data['data']['category_name']; Commented Aug 3, 2017 at 14:08
  • 1
    Probably you should try $data['data'][0]['category_name']. What's the output of print_r($data) in the foreach? Commented Aug 3, 2017 at 14:11

4 Answers 4

1

Things to consider:-

1.Your sub-array is again an array so you need to use foreach() on sub-array too. (So basically two foreach())

2.You need to close divs as well as foreach() loops too.

So code need to be like below:-

<?php
    foreach($var as $data){ 
        foreach($data['data'] as $dat){
 ?> 
    <div class="faqHeader"> <?php echo $dat['category_name'];?>            
        <div class="panel-group" id="<?php echo $dat['questions'];?>"><?php echo $dat['questions'];?></div>
        <div class="panel-group" id="<?php echo $dat['answer'];?>"><?php echo $dat['answer'];?></div>
    </div> 
<?php } }?>
Sign up to request clarification or add additional context in comments.

2 Comments

the one who down-voted please tell the reason. this code is perfectly fine.
@vinaykapoor glad to help you :):)
1

you can use two loops to simplify your task:-

foreach($var as $index=>data){
    echo $data['name']; // this will be your category name 
    foreach($data as $questionIndex=>$questionData){
        echo $questionData['question'];
        echo $questionData['answer'];
    }
}

Comments

0

Since your array contains multiple data and data contains multiple values itself, you need two foreaches here:

foreach($var as $item) {
    foreach($item['data'] as $info) {
         var_dump($info);
    }
}

Comments

0

Please try this code

<?php  
    $v1 = '';
    foreach($var as $data){ 
?> 
<div class="faqHeader"> <?php echo $data['data'][0]['category_name'];?> </div>             
<div class="panel-group" id="<?php echo $data['name'];?>">
<?php
    }
?>

You don't have any 'title' index in your array so you may change it to 'name'

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.