0

I have a dataset with 4 rows. I am using 2 foreach loops to get my data out. The outer foreach needs to loop once and I need the inner loop to loop 4x. Is there a way to do this or do I need to split the array?

  foreach($reports as $key=>$val)
  {
      if($val['rpt_type'] == 'Sooa')
      {
        foreach($val as $foo)
        {
          echo $foo['name'];
        }
      }
  }
12
  • you might want to add some code to your question, it's very unclear what's going on Commented May 3, 2009 at 12:33
  • 1
    ok, so what's the problem with this code? Commented May 3, 2009 at 12:37
  • The outer loop loops more than once. I need it to loop only once Commented May 3, 2009 at 12:39
  • :) So break out at the end of the first loop, right? Commented May 3, 2009 at 12:42
  • well, what other options are there? Commented May 3, 2009 at 12:43

2 Answers 2

1

I'm still unsure about how your data structure looks. To me, to be able to utilize a "rpt_type", it would have to look something like this:

$reports = array(
    0 => array(
        'rpt_type' => '...',
        ...
        'rows' => array(
            'name' => '...',
            ...
        ),
    ),
    1 => ...
);

You could then iterate over it with:

foreach($reports as $report) {
    if($report['rpt_type'] == 'Sooa') {
        foreach($report['rows'] as $row) {
            echo $row['name'];
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

First, check the contents of your $reports variable, using var_dump function of php:

var_dump($reports);

It'll print something like this:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}

Then you can implement your loop looking at the actual data you have, in whichever way your jagged arrays are formed.

Comments

Your Answer

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