7
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP 配列操作あれこれ

Last updated at Posted at 2015-09-26

PHPでよく使う配列操作のまとめ

各要素に同じ操作を適用する

例:配列の各要素を二倍にする

example1.php
$tmp = [1, 2, 3];
$ary = array_map(function($r){return $r*2;}, $tmp);
// $ary = [2, 4, 6]

各要素に第一引数に指定したコールバック関数を適用し、返り値のすべての要素をもつ配列を返す。

連想配列を要素に持つ配列(多次元配列)で、連想配列の特定の要素に同じ操作を適用する

例:連想引数の要素:priceを二倍にする

example2.php
$tmp = [
    ['id' => 1, 'price' => 100],
    ['id' => 2, 'price' => 200],
    ['id' => 3, 'price' => 300],
];
$double_price = function($r){
    $r['price'] = $r['price']*2;
    return $r;
};
$ary = array_map($double_price, $tmp);
/*
$ary = [
    ['id' => 1, 'price' => 200],
    ['id' => 2, 'price' => 400],
    ['id' => 3, 'price' => 600],
]
*/

連想配列を要素に持つ配列(多次元配列)で、連想配列の特定の要素のみを取り出す

例:連想配列の要素:idのみを取り出す

example3.php
$tmp = [
    ['id' => 1, 'price' => 100],
    ['id' => 2, 'price' => 200],
    ['id' => 3, 'price' => 300],
];
$ary = array_column($tmp, 'id');
// $ary = [1, 2, 3]

ただし、array_column関数はPHP5.5以上でないと使えない。
5.5未満のときはarray_map(function($r){return $r['id'];}, $tmp)

配列をフィルタする

例:連想配列の要素:priceが200以上のもののみを取り出す

example4.php
$tmp = [
    ['id' => 1, 'price' => 100],
    ['id' => 2, 'price' => 200],
    ['id' => 3, 'price' => 300],
];
$ary = array_filter($tmp, function($r){return $r['price'] >= 200;});
/*
$ary = [
    ['id' => 2, 'price' => 400],
    ['id' => 3, 'price' => 600],
]
*/
7
11
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?