0

$ 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]が来る前にdivを閉じる方法はわかりません。

4

4 に答える 4

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>';
}
于 2012-10-12T14:28:07.373 に答える
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>
于 2012-10-12T14:47:04.520 に答える
0

オブジェクトの配列をループして、最後のグループに別のグループ変数を保持するだけです。配列を2回ループして、新しい配列を生成する必要はありません。

$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>';
于 2012-10-12T14:28:45.293 に答える
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 } ?>
于 2012-10-12T14:33:57.943 に答える