如何将查询数据放在两个不同的数组中然后在两个表中回显?

时间:2016-08-02 05:54:58

标签: php mysql

select query

上运行table

过滤查询数据

如果是gender equal to Man,则将其全部放入数组men = array()

OR

如果它的gender is woman然后放入数组woman = array()

然后echo两个表

Men

1姓名,年龄,城市,国家等

2姓名,年龄,城市,国家等

3姓名,年龄,城市,国家等 。 。

Women

1姓名,年龄,城市,国家等

2姓名,年龄,城市,国家等

3姓名,年龄,城市,国家等 。 。 。

Men表将包含保存在Man数组中的Men()的所有行数据

Women表将包含保存在Woman数组中的Women()的所有行数据

注意: -

我尝试过这样的代码,但它的混乱我失败了: -

https://stackoverflow.com/questions/38653118/notice-undefined-offset-1-putting-mysql-query-data-in-while-loop

1 个答案:

答案 0 :(得分:1)

您的查询必须位于UNION

Select men.Name, men.age, men.city, men.country, 'Male' as 'gender' FROM men_table as men UNION ALL Select women.Name, women.age, women.city, women.country, 'Female' as 'gender FROM women_table as women;

所以你可以有一个查询输出:

|Name   |age    |city   |country|gender|
----------------------------------------
|male1  |21     |NY     |USA    |Male  |
|male2  |23     |CLV    |USA    |Male  |
|female1|25     |GS     |USA    |Female|
|female2|27     |CHG    |USA    |Female|

之后你可以循环到你的结果:

<?php 

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}
    $query = "Select men.Name, men.age, men.city, men.country, 'Male' as 'gender' FROM men_table as men UNION ALL Select women.Name, women.age, women.city, women.country, 'Female' as 'gender FROM women_table as women";

    $men = array();
    $women = array;

    if ($result = $mysqli->query($query)) {

        /* fetch associative array */
        while ($row = $result->fetch_assoc()) {
            if($row["gender"] == 'Male') {
                $men[] = $row[];
            }
            else {
                $women[] = $row[];
            }
        }

        print_r($men);
        print_r($women);

        /* free result set */
        $result->free();
    }

/* close connection */
$mysqli->close();
?>

输出将如下:

//$men array
    array(
        [0] => array(
                'Name' => 'male1', 
                'age' => '21', 
                'city' => 'NY', 
                'country' => 'USA', 
                'gender' => 'Male'
        ),
        [1] => array(
                'Name' => 'male2', 
                'age' => '23', 
                'city' => 'CLV', 
                'country' => 'USA', 
                'gender' => 'Male'
        )
    );

//$women array
    array(
        [0] => array(
                'Name' => 'female1', 
                'age' => '25', 
                'city' => 'GS', 
                'country' => 'USA', 
                'gender' => 'Female'
        ),
        [1] => array(
                'Name' => 'female2', 
                'age' => '27', 
                'city' => 'CHG', 
                'country' => 'USA', 
                'gender' => 'Female'
        )
    );