8
3

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.

日本情報クリエイト Engineer'sAdvent Calendar 2017

Day 22

PHP 配列関数を駆使してループを減らす

Last updated at Posted at 2018-05-11

特定のキーの並びに変える

array_fill_keys(),array_merge()を使う。

$keys = ["hoge", "hogehoge", "piyopiyo", "piyo"];
$keyArray = array_fill_keys($keys, null);
$tmp = [
    ["hoge" => 1, "piyo" => 2, "hogehoge" => 3, "piyopiyo" => 4],
    ["hoge" => 5, "piyo" => 6, "hogehoge" => 7, "piyopiyo" => 8],
];
$array = [];
foreach ($tmp as $val) {
    $array[] = array_merge($keyArray, $val);
}
print_r($array);

上記の出力結果

Array
(
    [0] => Array
        (
            [hoge] => 1
            [hogehoge] => 3
            [piyopiyo] => 4
            [piyo] => 2
        )

    [1] => Array
        (
            [hoge] => 5
            [hogehoge] => 7
            [piyopiyo] => 8
            [piyo] => 6
        )

)

DBから抽出したデーターをPHP側で並び替えたいときとかに使える

特定のキーの値のみ抽出

array_fill_keys(),array_intersect_key()を使う。

$keys = ["hoge","hogehoge"];
$array = ["hoge" => 1, "piyo" => 2, "hogehoge" => 3, "piyopiyo" => 4];
$array = array_intersect_key($array, array_fill_keys($keys, null));
print_r($array);

上記の出力結果

Array
(
    [hoge] => 1
    [hogehoge] => 3
)

特定のキーの値のみ排除

array_fill_keys(),array_diff_key()を使う。

$keys = ["hoge","hogehoge"];
$array = ["hoge" => 1, "piyo" => 2, "hogehoge" => 3, "piyopiyo" => 4];
$array = array_diff_key($array, array_fill_keys($keys, null));
print_r($array);

上記の出力結果

Array
(
    [piyo] => 2
    [piyopiyo] => 4
)

多次元配列を再構成

array_keys(),array_fill_keys(),array_column()を使う。

$tmp = [
    ["hoge" => 1, "piyo" => 2, "hogehoge" => 3, "piyopiyo" => 4],
    ["hoge" => 5, "piyo" => 6, "hogehoge" => 7, "piyopiyo" => 8],
];
$array = array_fill_keys(array_keys($tmp[0]), null);
array_walk($array, function(&$val, $key, $tmp){$val = array_column($tmp, $key);}, $tmp);
print_r($array);

上記の出力結果

Array
(
    [hoge] => Array
        (
            [0] => 1
            [1] => 5
        )

    [piyo] => Array
        (
            [0] => 2
            [1] => 6
        )

    [hogehoge] => Array
        (
            [0] => 3
            [1] => 7
        )

    [piyopiyo] => Array
        (
            [0] => 4
            [1] => 8
        )

)

emptyなものを排除

array_filter()を使う。

$array = [0,"hoge",null,"piyo",""];
$array = array_filter($array);
print_r($array);

上記の出力結果

Array
(
    [0] => hoge
    [1] => piyo
)
8
3
0

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
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?