Home > Software engineering >  Split stdClass Object into several blocks by value
Split stdClass Object into several blocks by value

Time:01-27

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [user_id] => 30
            [category] => 1
            [group] => 1
        )

    [1] => stdClass Object
        (
            [id] => 3
            [user_id] => 30
            [category] => 3,2
            [group] => 3
        )

)

Hello, i have this example data from database, i need to split blocks with multiple values(second block in this case) by [category] value, group 3 belongs to two categories, 3 and 2, could soomebody advise how to do it? than you in advance

CodePudding user response:

$data1 = new stdClass();
$data1->id = 1;
$data1->user_id = 30;
$data1->category = 1;
$data1->group = 1;

$data2 = new stdClass();
$data2->id = 3;
$data2->user_id = 30;
$data2->category = [ 3, 2 ];
$data2->group = 3;

$data = [ $data1, $data2 ];

$result = [];
foreach ($data as $item) {
  if (is_array($item->category)) {
    foreach($item->category as $category) {
      $clone = clone $item;
      $clone->category = $category;
      $result[] = $clone;
    }
  } else {
    $result[] = $item;
  }
}
  •  Tags:  
  • Related