$ result是一个如下所示的数组:
Array (
[0] => stdClass Object (
[Key_1] => a
[Key_2] => 10
)
[1] => stdClass Object (
[Key_1] => b
[Key_2] => 10
)
[2] => stdClass Object (
[Key_1] => c
[Key_2] => 20
)
)
如何在包含在像
这样的div中的[Key_2]分组的foreach循环中回显$ result<div class="new_Key_2">
Key_2: 10
------------
Key_1: a
Key_1: b
</div>
<div class="new_Key_2">
Key_2: 20
------------
Key_1: c
</div>
我知道如何通过检查[Key_2]是否已更改来打开div,而不是在新[Key_2]出现之前如何关闭它。
答案 0 :(得分:3)
您需要的PHP代码,您只需要使用它来匹配您的HTML输出需求。
<?php
$result = array();
foreach ($array as $object)
{
$result[$object->key_2][] = $object->key_1;
}
foreach ($result as $key_2 => $keys)
{
echo '<h1>'.$key_2.'</h1>';
echo '<p>';
echo implode('<br>', $keys);
echo '</p>';
}
答案 1 :(得分:0)
只需遍历对象数组,并将一个单独的组变量保存到最后一个组。 无需循环数组两次并生成新数组。
$group = false;
foreach($array as $object) {
if($group !== false)
echo '</div>';
if($group != $object->Key_2) {
echo '<div class="new_key_2">';
}
$group = $object->Key_2;
// do stuff
}
if($group !== false)
echo '</div>';
答案 2 :(得分:0)
假设您的初始数组为$my_array
// Generating a new array with the groupped results
$new_array = array();
foreach ($my_array as $element)
{
$new_array[$element->Key_2][] = $element->Key_1;
}
然后在视图层中,您可以依次回显每个div /元素
<?php foreach ($new_array as $key => $items) { ?>
<div class="new_Key_2">
Key_2 : <?php echo $key; ?><br />
---------------------------<br />
<?php echo implode('<br />', $items); ?>
</div>
<?php } ?>
答案 3 :(得分:0)
您可以使用array_reduce
$stdA = new stdClass();
$stdA->Key_1 = "a";
$stdA->Key_2 = 10;
$stdB = new stdClass();
$stdB->Key_1 = "b";
$stdB->Key_2 = 10;
$stdC = new stdClass();
$stdC->Key_1 = "a";
$stdC->Key_2 = 20;
# Rebuilding your array
$array = Array("0" => $stdA,"1" => $stdB,"2" => $stdC);
# Group Array
$array = array_reduce($array, function ($a, $b) {$a[$b->Key_2][] = $b;return $a;});
#Output Array
foreach ( $array as $key => $value ) {
echo '<div class="new_Key_2">';
echo "<h3> Key_2 : $key </h3>";
foreach ( $value as $object )
echo "<p>Key_1 : $object->Key_1</p>";
echo '</div>';
}
输出
<div class="new_Key_2">
<h3>Key_2 : 10</h3>
<p>Key_1 : a</p>
<p>Key_1 : b</p>
</div>
<div class="new_Key_2">
<h3>Key_2 : 20</h3>
<p>Key_1 : a</p>
</div>