2012-10-12 29 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 } ?>