-1

この配列をhouseidでグループ化するにはどうすればよいですか?

Array
(
    [0] => stdClass Object
        (
            [id] => 1111
            [houseid] => 58
            [price] => 2995
        )

    [1] => stdClass Object
        (
            [id] => 1112
            [houseid] => 58
            [price] => 4050
        )

    [2] => stdClass Object
        (
            [id] => 1114
            [houseid] => 60
            [price] => 1695
        )

    [3] => stdClass Object
        (
            [id] => 1115
            [houseid] => 60
            [price] => 2250
        )

    [4] => stdClass Object
        (
            [id] => 1116
            [houseid] => 60
            [price] => 2295
        )
)

ハウスIDの合計価格を計算し、いくつかの計算/条件を実行する必要があります。この配列をグループ化すると簡単になります...

この配列を次のような形式にフォーマットできますか

Array
(
    [58] => stdClass Object(
        [0] => stdClass Object
        (
            [id] => 1111
            [price] => 2995
        )
        [1] => stdClass Object
        (
            [id] => 1112
            [houseid] => 58
            [price] => 4050
        )
    )
    [60] => stdClass Object(
        [0] => stdClass Object(
            [id] => 1114
            [price] => 1695
        )
        [1] => stdClass Object
        (
            [id] => 1115
            [price] => 2250
        )
        [2] => stdClass Object
        (
            [id] => 1116
            [price] => 2295
        )
)

または、誰かが私に提案することができますか、家の合計価格を数えるために元の配列をループする方法はありますか?

4

1 に答える 1

3

使用できますarray_reduce

$data = array_reduce($data, function ($a, $b) {
    $id = $b->houseid;
    unset($b->houseid);
    $a[$id][] = $b;
    return $a;
});

var_dump($data);

出力

array (size=2)
  58 => 
    array (size=2)
      0 => 
        object(stdClass)[1]
          public 'id' => int 1111
          public 'price' => int 2995
      1 => 
        object(stdClass)[2]
          public 'id' => int 1112
          public 'price' => int 4050
  60 => 
    array (size=3)
      0 => 
        object(stdClass)[3]
          public 'id' => int 1114
          public 'price' => int 1695
      1 => 
        object(stdClass)[4]
          public 'id' => int 1115
          public 'price' => int 2250
      2 => 
        object(stdClass)[5]
          public 'id' => int 1116
          public 'price' => int 2295

フルライブデモ

于 2012-11-27T20:10:16.673 に答える