簡體   English   中英

使用一列作為鍵,另一列作為值,從 oF 行數組生成關聯數組

[英]Generate an associative array from an array oF rows using one column as keys and another column as values

我有一個 MySQL 結果集,每行有 2 個值。

每次循環遍歷這些結果時,我都想將它們添加到數組中。

我希望一個值作為鍵,另一個作為數組值。

我試過這個,但它似乎不起作用:

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

如果我有:

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

我想生成:

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

為什么不只是使用

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

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

對於此任務,使用array_column()而不是foreach()更優雅/富有表現力/現代/簡潔。

第一個參數是行的輸入數組。
第二個參數是要成為 output 數組中的值的列。
第三個參數是要成為 output 數組中的鍵的列。

代碼:(演示

$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',
)

如果您想分配新的第一級鍵但保持行不變, null作為本機 function 調用的第二個參數編寫。

代碼:(演示

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',
  ),
)

一種較少實現的無功能技術是在無主體的foreach()循環中使用數組解構。 演示

$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);

這相當於早期的答案,建議這樣做:

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

Output:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM