我有这段代码,希望从中获得包含所有值的单个数组。

$sql = "SELECT * FROM interest where interest='".$interest."' and userid!='".$myuserid."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
    {
        while($row = mysqli_fetch_assoc($result))
            {
                $userid = $row["userid"];

                if($searchtype == 'both')
                    {
                        $sql2 = "SELECT * FROM register where id='".$userid."' and  discover = 'on' and id!='".$myuserid."'";
                        $result2 = mysqli_query($conn, $sql2);
                        if (mysqli_num_rows($result2) > 0)
                            {
                                while($row2 = mysqli_fetch_assoc($result2))
                                    {
                                        echo "<pre>";
                                        print_r($row2);
                                        echo "</pre>";
                                    }
                            }
                    }
            }
    }

我得到的O/P是这样的
Array
(
    [id] => 1
    [email] => A1
    [username] =>B1
    [password] => C1
    [gender] => C1
)

Array
(
    [id] => 2
    [email] => A2
    [username] => B2
    [password] => C2
    [gender] => D2
)
Array
(
    [id] => 3
    [email] => A3
    [username] => B3
    [password] => C3
    [gender] => D3
)

但我希望像这样在单个数组中获取所有数据
Array
(
    [0] => Array
        (
             [id] => 1
             [email] => A1
             [username] =>B1
             [password] => C1
             [gender] => C1
        )

    [1] => Array
        (
            [id] => 2
            [email] => A2
            [username] => B2
            [password] => C2
            [gender] => D2
        )
     [2] => Array
        (
            [id] => 3
            [email] => A3
            [username] => B3
            [password] => C3
            [gender] => D3
        )
}

谁能告诉我我该怎么做

最佳答案

在while循环开始之前像$user_data = array();一样获取一个数组变量,在内部循环中,您必须设置$user_data[] = $row2;

if (mysqli_num_rows($result) > 0) {
    $user_data = array();
    while($row = mysqli_fetch_assoc($result)) {
            $userid = $row["userid"];
            if($searchtype == 'both') {
                    $sql2 = "SELECT * FROM register where id='".$userid."' and  discover = 'on' and id!='".$myuserid."'";
                    $result2 = mysqli_query($conn, $sql2);
                    if (mysqli_num_rows($result2) > 0) {
                            while($row2 = mysqli_fetch_assoc($result2)) {
                                    $user_data[] = $row2;
                                }
                        }
                }
        }
   print_r($user_data);   //Print here your user_data outside the loop.
}

关于mysql - 合并多个阵列到单个阵列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31332545/

10-09 15:21