0

I'm trying to group the arrays of a query, using the PHP foreach loop, to a group of objects without sub objects. But I'm not getting it, I've tried it in several ways. I'm using the following loop with foreach:

public function array_to_object($array)
        {
          $obj = new stdClass;
          foreach($array as $k => $v) {
              if(is_array($v)){
                $obj->{$k} = $this->array_to_object($v); //RECURSION
                } else {
                    $obj->{$k} = $v;
              }
          }
          return $obj;
        }

    $users = $this->array_to_object($users);
    print_r((array)$users);

I have this result:

Array
(
    [0] => stdClass Object
        (
            [_id] => 12
            [username] => lucaspedro
            [first_name] => Lucas
            [user_role] => stdClass Object
                (
                    [ur_name] => Admin
                )

        )

    [1] => stdClass Object
        (
            [_id] => 32
            [username] => joaosilva
            [first_name] => Joao
            [user_role] => stdClass Object
                (
                    [ur_name] => Member
                )
        )
)

But I need this result:

Array
(
    [0] => stdClass Object
        (
            [_id] => 12
            [username] => lucaspedro
            [first_name] => Lucas
            [ur_name] => Admin
        )

    [1] => stdClass Object
        (
            [_id] => 32
            [username] => joaosilva
            [first_name] => Joao
            [ur_name] => Member
        )
)
halfer
  • 19,824
  • 17
  • 99
  • 186
  • Possible duplicate of [How to Flatten a Multidimensional Array?](https://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array) – Philipp Maurer Jan 22 '18 at 12:04
  • It is not exactly the same as your case, but all you need to do is alter the code a bit and use it in an `array_map` over your initial array instead of using it on it directly – Philipp Maurer Jan 22 '18 at 12:06

1 Answers1

0

A simple foreach can do the trick for you.

foreach($array as $k=>$v){
        $array[$k]->ur_name = $v->user_role->ur_name;
        unset($array[$k]->user_role);
    }
print_r($array);
Sohel0415
  • 9,523
  • 21
  • 30