PHP array_column()関数
例
レコードセットから名前の列を取得します。
<?php
// An array that represents a possible record set returned from a database
$a = array(
array(
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
),
array(
'id' => 4767,
'first_name' => 'Ben',
'last_name' => 'Smith',
),
array(
'id' => 3809,
'first_name' => 'Joe',
'last_name' => 'Doe',
)
);
$last_names = array_column($a, 'last_name');
print_r($last_names);
?>
出力:
Array
(
[0] => Griffin
[1] => Smith
[2] => Doe
)
定義と使用法
array_column()関数は、入力配列の単一の列から値を返します。
構文
array_column(array, column_key, index_key)
パラメータ値
Parameter | Description |
---|---|
array | Required. Specifies the multi-dimensional array (record-set) to use. As of PHP 7.0, this can also be an array of objects. |
column_key | Required. An integer key or a string key name of the column of values to return. This parameter can also be NULL to return complete arrays (useful together with index_key to re-index the array) |
index_key | Optional. The column to use as the index/keys for the returned array |
技術的な詳細
戻り値: | 入力配列から単一の列を表す値の配列を返します |
---|---|
PHPバージョン: | 5.5+ |
その他の例
例
「id」列でインデックス付けされた、レコードセットからの名前の列を取得します。
<?php
// An array that represents a possible record set returned from a database
$a = array(
array(
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
),
array(
'id' => 4767,
'first_name' => 'Ben',
'last_name' => 'Smith',
),
array(
'id' => 3809,
'first_name' => 'Joe',
'last_name' => 'Doe',
)
);
$last_names = array_column($a, 'last_name', 'id');
print_r($last_names);
?>
出力:
Array
(
[5698] => Griffin
[4767] => Smith
[3809] => Doe
)
❮PHP配列リファレンス