2012-10-12 28 views
0

$结果是一个数组,看起来像这样:分组通过钥匙阵列在foreach循环

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 
    ) 
) 

我怎么能回声$结果通过[Key_2]分组foreach循环裹着像一个div

<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

可以群的阵列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> 
+0

**解析错误:**语法错误,在线路意外T_FUNCTION _ $阵列= array_reduce($阵列,..._ – joko13

+0

什么版本的PHP您使用的是???请参阅现场演示:http://codepad.viper-7.com/xGiSXR – Baba

+0

@ joko13如果您的php小于5.3,请使用此代码http://codepad.org/pbUI1Grz – Baba

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>'; 
} 
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>'; 
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 } ?>