Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
]
like image 352
mrpatg Avatar asked Dec 14 '25 18:12

mrpatg


1 Answers

Why not just use

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

?

like image 160
kennytm Avatar answered Dec 17 '25 07:12

kennytm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!