如何在PHP中的foreach循环内对数组中的子对象进行分组?

时间:2018-01-22 12:02:11

标签: php arrays object foreach

我尝试使用PHP foreach循环将查询数组分组到没有子对象的一组对象。但我没有得到它,我已经在几个方面尝试过它。我在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);

我有这个结果:

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
                )
        )
)

但我需要这个结果:

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
        )
)

1 个答案:

答案 0 :(得分:0)

一个简单的foreach可以帮到你。

foreach($array as $k=>$v){
        $array[$k]->ur_name = $v->user_role->ur_name;
        unset($array[$k]->user_role);
    }
print_r($array);