Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split stdClass Object into several blocks by value

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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;
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading