phparraysmysqliarray-key

Generating a php array from mysql and want to use ID from db as array keys


The current output is..

Array
(
    [0] => Array
        (
            [ID] => 20
            [name] => Peter
            [datetime] => Tuesday 26th Oct 21 3:50am
        )

    [1] => Array
        (
            [ID] => 21
            [name] => Paul
            [datetime] => Tuesday 26th Oct 21 4:44am
        )
)

I would like the array output to be..

Array
(
    [20] => Array
        (
            [ID] => 20
            [name] => Peter
            [datetime] => Tuesday 26th Oct 21 3:50am
        )

    [21] => Array
        (
            [ID] => 21
            [name] => Paul
            [datetime] => Tuesday 26th Oct 21 4:44am
        )
)

The code I am currently using to generate the array is..

$sql=mysqli_query($conn,"SELECT * FROM `live`");
    /*every time it fetches the row, adds it to array...*/
    while($liveuserdata[]=mysqli_fetch_array($sql, MYSQLI_ASSOC));

I can't show you what i've tried as I don't know where to begin dispite several rephrased searches :-/


Solution

  • It is as simple as:

    $sql = mysqli_query($conn,"SELECT * FROM `live`");
    $liveuserdata = [];
    while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)) {
        $liveuserdata[$row['ID']] = $row;
    }