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:
我正在尝试很好地输出一个数据数组(使用Kohana v2.3.4),并且我认为必须有一个更有效和更优雅的方法来做到这一点。我的数组看起来像这样:
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?
有没有更好的方法来解决这个问题?
2 个解决方案
#1
1
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:
你不能逃避使用嵌套循环(除非你使用array_walk等),但你可以通过利用变量替换而不使用大量的字符串连接来完成:
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:
您还可以将它与extract()组合以获得更清晰的字符串:
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>";
}
}
#2
1
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?
对于这个嵌套循环,你有什么问题?
#1
1
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:
你不能逃避使用嵌套循环(除非你使用array_walk等),但你可以通过利用变量替换而不使用大量的字符串连接来完成:
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:
您还可以将它与extract()组合以获得更清晰的字符串:
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>";
}
}
#2
1
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?
对于这个嵌套循环,你有什么问题?