PHP - 在foreach循环期间修改数组

时间:2015-06-02 12:04:02

标签: php arrays multidimensional-array

public function getUserList($user_id){

        $list_query = "SELECT ACTUAL_USER_ID FROM TABLE WHERE USER_ID = ".$user_id." ";
        $result = parent::queryresult($list_query);
        return $result;
    }


foreach ($result as $uresult){ //$result contains user_id
        $userlist[] = $classObject->getUserList($uresult['USER_ID']);
}

下面的循环停电

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [ACTUAL_USER_ID] => 133
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [ACTUAL_USER_ID] => 122
                )

        )

)

如何删除嵌套数组并使其如下所示

Array
(
    [0] => Array
        (

            [ACTUAL_USER_ID] => 133

        )

    [1] => Array
        (
            [ACTUAL_USER_ID] => 122

        )

)

2 个答案:

答案 0 :(得分:3)

使用方括号[]访问数组元素

foreach ($result as $uresult){ //$result contains user_id
  $userlist[] = $classObject->getUserList($uresult['USER_ID'])[0];
}

编辑:在不同/旧版本的PHP上,您需要先将数组放入变量:

foreach ($result as $uresult){ //$result contains user_id
  $row = $classObject->getUserList($uresult['USER_ID']);
  $userlist[] = $row[0];
}

答案 1 :(得分:2)

更改foreach声明如下

foreach ($result as $uresult){ //$result contains user_id
       $res = $classObject->getUserList($uresult['USER_ID']);
      if(isset($res[0]))
        $userlist[]  = $res[0];
}