Help us understand the problem. What is going on with this article?

PHP 配列操作あれこれ

More than 5 years have passed since last update.

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],
]
*/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away