1

I am having issue with execution of nested foreach loop execution for desired result. Below is the scenario:

Following are result in two arrays

Result1:

Array ( [0]=> Array ( [questionID] => 103 [answer] => Female [answer_cnt] => 8 ) 
       [1] => Array ( [questionID] => 103 [answer] => Male [answer_cnt] => 9 )
      ) 

Result2

Array ( [0] => Male [1] => Female )

my code using foreach loop is below

 foreach($qrs as $qrow)

        {       foreach($d as $q){

                    echo"<br>".$q;                                                              
                  echo $qrow['answer_cnt']."<br>";}
        }

it will get output :

Male 8

Female8

Male 9

Female9

But My Expected output is

 Female 8

 Male 9
1
  • why would you expect that? It isn't what you are doing. Commented Sep 12, 2014 at 5:00

4 Answers 4

1

You don't need to loop on the second. Just use the first one.

foreach($qrs as $qrow) {
    echo $qrow['answer'] . ' ' . $qrow['answer_cnt'] . '<br/>';
}

Its quite unclear why do you need the second array but if you want to include it (which makes no sense), just include an if.

foreach($qrs as $qrow) {
    foreach($d as $q) {
        if($qrow['answer'] == $q) {
            echo $qrow['answer'] . ' ' . $qrow['answer_cnt'] . '<br/>';
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

ghost!plz give ur previous answer that will help me!
@NikhilMusale what do you mean previous answer? i didn't revise
@NikhilMusale sure glad it went your way
0

Your second array is useless. just do:

foreach($qrs as $qrow)
    {      
              echo"<br>".$qrow['answer']." ";                                                              
              echo $qrow['answer_cnt']."<br>";}
    }

Comments

0

use this...

 foreach($qrs as $qrow)
        {   
            foreach($d as $q)
            {
                if(in_array($q, $qrow))
                {
                    echo"<br>".$q;                                                              
                    echo $qrow['answer_cnt']."<br>";    
                }
            }
        }

Comments

0
$arr = array(
    array( 'questionID' => 103, 'answer' => 'Female',  'answer_cnt' => 8),
    array( 'questionID' => 103, 'answer' => 'Male',  'answer_cnt' => 9)
);

if(count($arr) > 0) {
    foreach($arr as $val) {
        echo "$val[answer] $val[answer_cnt] <br />";
    }
}

you can also try this one.

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.