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'];
}
}
}
-
you might want to add some code to your question, it's very unclear what's going onSilentGhost– SilentGhost2009年05月03日 12:33:28 +00:00Commented May 3, 2009 at 12:33
-
1ok, so what's the problem with this code?SilentGhost– SilentGhost2009年05月03日 12:37:55 +00:00Commented May 3, 2009 at 12:37
-
The outer loop loops more than once. I need it to loop only onceTom– Tom2009年05月03日 12:39:06 +00:00Commented May 3, 2009 at 12:39
-
:) So break out at the end of the first loop, right?Tom– Tom2009年05月03日 12:42:22 +00:00Commented May 3, 2009 at 12:42
-
well, what other options are there?SilentGhost– SilentGhost2009年05月03日 12:43:52 +00:00Commented May 3, 2009 at 12:43
2 Answers 2
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'];
}
}
}
Comments
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.