PHP

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
)