3

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'
]
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
mrpatg
  • 10,001
  • 42
  • 110
  • 169

3 Answers3

7

Why not just use

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

?

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
3
$dataarray[ $row['id'] ] = $row[ 'data' ];
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
disc0dancer
  • 9,185
  • 11
  • 36
  • 46
1

It is more elegant/expressive/modern/concise to use array_column() instead of a foreach() for this task.

The first parameter is the input array of rows.
The second parameter is the column to become the values in the output array.
The third parameter is the column to become the keys in the output array.

Code: (Demo)

$array = [
    ['id' => 1, 'key' => 'foo', 'data' => 'a'],
    ['id' => 2, 'key' => 'bar', 'data' => 'b'],
    ['id' => 3, 'key' => 'barf', 'data' => 'c'],
];

var_export(
    array_column($array, 'data', 'id')
);

Output:

array (
  1 => 'a',
  2 => 'b',
  3 => 'c',
)

The Laravel equivalent method to call on a collection is pluck() like:

$collection->pluck('data', 'id')

If you'd like to assign new first level keys but leave the rows unchanged, you write null as the second parameter of the native function call.

Code: (Demo)

var_export(
    array_column($array, null, 'id')
);

Output:

array (
  1 => 
  array (
    'id' => 1,
    'key' => 'foo',
    'data' => 'a',
  ),
  2 => 
  array (
    'id' => 2,
    'key' => 'bar',
    'data' => 'b',
  ),
  3 => 
  array (
    'id' => 3,
    'key' => 'barf',
    'data' => 'c',
  ),
)

A lesser realized, functionless technique would be to use array destructuring inside a body-less foreach() loop. (Demo)

$array = [
    ['id' => 1, 'data' => 'a'],
    ['id' => 2, 'data' => 'b'],
    ['id' => 3, 'data' => 'c'],
];

$result = [];
foreach ($array as ['id' => $id, 'data' => $result[$id]]);
var_export($result);

This is equivalent to the earlier answers which advise this:

foreach ($array as $row) {
    $result[$row['id']] = $row['data'];
}

Output:

array (
  1 => 'a',
  2 => 'b',
  3 => 'c',
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136