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'
]

3 Answers 3

8

Why not just use

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

?

Sign up to request clarification or add additional context in comments.

Comments

5

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

Also, array_combine(array_column($array, 'id'), array_column($array, 'data')) is working too hard and should never be used.

The first parameter of array_column() is the input array of rows.
The second parameter is the column for the values in the output array.
The third parameter is the column for 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',
)

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.