views:

72

answers:

2

I'm trying to nicely output a data array (with Kohana v2.3.4), and am thinking there has to be a more efficient and elegant way to do this. My array looks like this:

array('category_id' => value, 'category_title' => value, 'posts' => array( 'id' => value, 'title' => value, ... ))


And here's how I'm outputting it in my view (some array values are omitted from this example for the sake of simplicity):

foreach($data as $d) {
    echo '<h3>'.$d['category_title'].'</h3>';
    foreach($d['posts'][0] as $p) {
     echo '<p>'.$p['title'].$p['id'].'</p>';
    }
}

Is there a better way to go about this with the array I have?

+1  A: 

Apart from a minor error:

foreach ($data as $d) {
  echo '<h3>'.$d['category_title'].'</h3>';
  foreach($d['posts'] as $p) {
    echo '<p>'.$p['title'].$p['id'].'</p>';
  }
}

no there isn't.

What's your issue with a nested loop for this?

cletus
$d['posts'][0] wasn't an error - without the [0] the second foreach doesn't access any of the variables I need.I don't have a problem with nested loops per se, this just seems a messy way to go about it.
Deca
+1  A: 

You can't escape from using nested loop (unless if you use array_walk etc) but you can make do without using lots of string concatenation by taking advantage of variable substitution:

foreach($data as $d) {
    echo "<h3>{$d['category_title']}</h3>";
    foreach($d_posts[0] as $p) {
        echo "<p>{$p['title']} {$p['id']}</p>";
    }
}

You can also combine it with extract() for cleaner strings:

foreach($data as $d) {
    extract($d, EXTR_PREFIX_ALL, 'd_');
    echo "<h3>$d_category_title</h3>";
    foreach($d_posts[0] as $p) {
        extract($p, EXTR_PREFIX_ALL, 'p_');
        echo "<p>$p_title $p_id</p>";
    }
}
Lukman
Thanks Lukman. I've used extract() but never with EXTR_PREFIX_ALL - nice suggestion.
Deca