特定のキーの並びに変える
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
)