Created
September 10, 2012 09:54
-
-
Save k-holy/3690037 to your computer and use it in GitHub Desktop.
配列フィルタいろいろ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme; | |
// フィルタに通れば上書き、なければそのまま | |
$data1 = array( | |
'name ' => '', | |
'age' => '20', | |
'notes' => 'HOGE', | |
); | |
$data2 = array( | |
'name' => 'TEST', | |
'age' => null, | |
'notes' => 'FUGA', | |
); | |
echo '<pre>'; | |
printf('$data1 = %s', print_r($data1, true)); | |
echo '</pre>'; | |
echo '<pre>'; | |
printf('$data2 = %s', print_r($data2, true)); | |
echo '</pre>'; | |
$filter = function($value) { | |
return (isset($value) && strlen($value) >= 1); | |
}; | |
$merged_data = array_replace( | |
array_filter($data1, $filter), | |
array_filter($data2, $filter)); | |
echo '<pre>'; | |
printf('$merged_data = %s', print_r($merged_data, true)); | |
echo '</pre>'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme; | |
// array_intersect_ukey()を使って配列の要素をキーでフィルタ | |
// via http://blog.sarabande.jp/post/24178664526 | |
$accept_keys = array( | |
'name','age', | |
); | |
$data = array( | |
'invalid' => 'HOGE', | |
'name' => 'test', | |
'unko' => 'UNKO', | |
'age' => '20', | |
); | |
echo '<pre>'; | |
printf('$data = %s', print_r($data, true)); | |
echo '</pre>'; | |
// One-linerで書くなら | |
$filtered_data = array_intersect_ukey($data, $data, | |
function($key1, $key2) use ($accept_keys) { | |
return in_array($key1, $accept_keys) ? 0 : 1; | |
} | |
); | |
echo '<pre>'; | |
printf('$filtered_data = %s', print_r($filtered_data, true)); | |
echo '</pre>'; | |
// フィルタを外部に定義するなら | |
$filter = function($key) use ($accept_keys) { | |
return in_array($key, $accept_keys); | |
}; | |
$filtered_data = array_intersect_ukey($data, $data, | |
function($key1, $key2) use ($filter) { | |
return $filter($key1) ? 0 : 1; | |
} | |
); | |
echo '<pre>'; | |
printf('$filtered_data = %s', print_r($filtered_data, true)); | |
echo '</pre>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment