phparraysassociative-arrayflattenarray-column

Generate an associative array from an array of rows using one column as keys and another column as values


I have a MySQL result set with 2 values in each row.

Each time I loop through these results, I want to add them to an array.

I want one value to be the key, and the other to be the array value.

I tried this, but it doesn't seem to work:

$dataarray[] = $row['id'] => $row['data'];

If I have:

$resultSet = [
    ['id' => 1, 'data' => 'one'],
    ['id' => 2, 'data' => 'two'],
    ['id' => 3, 'data' => 'three']
];

I want to generate:

[
    1 => 'one',
    2 => 'two',
    3 => 'three'
]

Solution

  • Why not just use

    $dataarray[$row['id']] = $row['data'];
    

    ?