How to get data in a one dimensional array for a single column?

Viewed 190

I am using MYSQLI query to extract data into an array. But when printing the array content, it looks that data is being populated into sub array. This is my code:


<?php
require_once 'database.php';

// Choose the y-axis
$sql = "SELECT `O3` FROM giordan_mod ORDER BY id DESC LIMIT 4";
$resulty = mysqli_query($conn, $sql);
$datay = [];
while($row = mysqli_fetch_array($resulty, MYSQLI_NUM))
{
      $datay[] = $row;
}

echo '<pre>'; print_r($datay);'</pre>';
?>

<?php
$test = array(4, 6, 9, 15);
echo '<pre>'; print_r($test);'</pre>';
?>

But when printing the array, the result are as follows:

    Array
(
    [0] => Array
        (
            [0] => 40.25
        )

    [1] => Array
        (
            [0] => 39.64
        )

    [2] => Array
        (
            [0] => 40.13
        )

    [3] => Array
        (
            [0] => 40.28
        )

)

Array
(
    [0] => 4
    [1] => 6
    [2] => 9
    [3] => 15
)

But I would like that MYSQLI query input data into an array and not sub array. That is I need $datay array looks as $test array.

1 Answers

mysqli_fetch_array() returns an array representing a row of data from your SQL command. Even if you only fetch a single command, it will always be an array. To fetch fetch a single column you need to use mysqli_fetch_column().

You can use PDO instead. It is easier and offers more functionality including a method to fetch a single function.

If you are stuck with mysqli, then you can use a loop and fetch the single column yourself.

$sql = "SELECT `O3` FROM giordan_mod ORDER BY id DESC LIMIT 4";
$resulty = mysqli_query($conn, $sql);
$datay = [];
foreach($resulty as $row) {
    $datay[] = $row['O3'];
}

or even simpler:

$sql = "SELECT `O3` FROM giordan_mod ORDER BY id DESC LIMIT 4";
$resulty = mysqli_query($conn, $sql);
$datay = array_column($resulty->fetch_all(MYSQLI_ASSOC), 'O3');
Related