将两列合并为一个数组

时间:2018-05-06 10:41:33

标签: php arrays merge

我想将我的两个列(yanlis_cevaplar, cevap_icerik)合并到一个数组中,这里的代码在打印时只给出了一列数组(yanlis_cevaplar)。

我该如何解决?

$cevaplar = "SELECT yanlis_cevaplar FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));

$cevap1 = array(); //create empty array
while ($row = $cevap_sonuc->fetch_array()) { //loop to get all results
    $cevap1[] = $row; //grab everything and store inside array
}

$cevaplar2 = "SELECT cevap_icerik FROM cevaplar";
$cevap_sonuc2 = $conn->query($cevaplar) or die(mysqli_error($conn));

$cevap2 = array(); //create empty array
while ($row = $cevap_sonuc2->fetch_array()) { //loop to get all results
    $cevap2[] = $row; //grab everything and store inside array
}

$tumcevaplar = array_merge($cevap1, $cevap2);

print_r($tumcevaplar);

1 个答案:

答案 0 :(得分:2)

您可以只在一个查询中获取所需的所有列,而不是进行多次查询:

$cevaplar = "SELECT yanlis_cevaplar, cevap_icerik FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));

// Now you can fetch all the rows straight away without any loop.
// The MYSQLI_ASSOC will return each row as an associative array
$result = $cevap_sonuc->fetch_all(MYSQLI_ASSOC);

print_r($result);

这将导致类似这样的事情:

Array
(
    [0] => Array
        (
            [yanlis_cevaplar] => some value
            [cevap_icerik] => some value
        )

    [1] => Array
        (
            [yanlis_cevaplar] => some value
            [cevap_icerik] => some value
        )

    ... and so on ..    

)

如果这不是您想要的,那么您需要向我们展示一个示例。

我还建议您阅读一些基本的SQL教程。 SELECT的工作原理是SQL 101.以下是许多指南之一:https://www.tutorialspoint.com/mysql/mysql-select-query.htm