vinay kapoor
vinay kapoor

Reputation: 83

Print the specific values from the array

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

Upvotes: 0

Views: 347

Answers (4)

Asad Khan
Asad Khan

Reputation: 116

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'];
    }
}

Upvotes: 1

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

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

Upvotes: 1

smupyknight
smupyknight

Reputation: 174

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'

Upvotes: 0

Peon
Peon

Reputation: 8030

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);
    }
}

Upvotes: 0

Related Questions