如何使用PHP / MySQL从2个独立的ID创建两个单独的数组?

时间:2018-01-27 22:21:53

标签: php mysql mysqli

如何从MySQL数据库创建两个数组?我想使用id 1作为我的第一个数组,id 2作为我的第二个数组。我的目标是创建两个数组并从重复项中创建一个单独的数组。

<?php include 'connect.php';

$var1 = '1';
$var2 = '2';

$sql = "SELECT * FROM data WHERE id=$var1";
$result = $conn->query($sql);
if($result->num_rows > 0){
    while($row = $result->fetch_assoc()){

            $a1 = $row["a1"];
            $a2 = $row["a2"];
            $a3 = $row["a3"];
            $a4 = $row["a4"];

            $b1 = $row["a4"];
            $b2 = $row["a4"];
            $b3 = $row["a4"];
            $b4 = $row["a4"];

    }

    $array1 = array($a1, $a2, $a3, $a4);
    $array2 = array($b1, $b2, $b3, $b4);
    $result = array_intersect($array1, $array2);

echo implode(" ",$array1);
echo "<br>";
echo implode(" ",$array2);
echo "<br>";
echo implode(" ",$result);

} else {
    echo "0 results";
} 
$conn->close();  
?>

1 个答案:

答案 0 :(得分:1)

ID值为2的分辨率无需更改$result变量名称,但无论如何都应该这样做,只是为了让它更友好。

<?php
include 'connect.php';

$var1 = '1';
$var2 = '2';

$sql = "SELECT * FROM data WHERE id=$var1 OR id=$var2";
$result = $conn->query($sql);
if($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
        if($row['id'] == $var1){
            $a1 = $row['a1'];
            $a2 = $row['a2'];
            $a3 = $row['a3'];
            $a4 = $row['a4'];
        } else if($row['id'] == $var2){
            $b1 = $row['a1'];
            $b2 = $row['a2'];
            $b3 = $row['a3'];
            $b4 = $row['a4'];
        }
    }
    $array1 = array($a1, $a2, $a3, $a4);
    $array2 = array($b1, $b2, $b3, $b4);
    $result = array_intersect($array1, $array2);

    echo implode(' ', $array1);
    echo '<br>';
    echo implode(' ', $array2);
    echo '<br>';
    echo implode(' ', $result);
} else {
    echo '0 results';
} 
$conn->close();  
?>