2016-02-02 34 views
0

我從var_export($post_meta);的結果從$post_meta = get_post_meta(80)得到以下數組;在多維陣列上的filter_input_array

array (
    '_edit_last' => 
    array (
    0 => '1', 
), 
    '_edit_lock' => 
    array (
    0 => '1451326767:1', 
), 
    '_sidebar' => 
    array (
    0 => 'Kies Sidebar', 
), 
    '_wp_page_template' => 
    array (
    0 => 'page-pop.php', 
), 
    'custom_sidebar_per_page' => 
    array (
    0 => 'default', 
), 
    '_cat_id' => 
    array (
    0 => '21', 
), 
    '_order_by' => 
    array (
    0 => 'date', 
), 
    '_asc' => 
    array (
    0 => 'DESC', 
), 
    '_post_count' => 
    array (
    0 => '5', 
), 
    '_days' => 
    array (
    0 => '0', 
), 
    '_custom_sidebar_per_page' => 
    array (
    0 => 'default', 
), 
) 

現在我需要過濾一些這些值,如果他們存在,所以我可以安全地使用它們。我做了以下

$args = [ 
    '_cat_id' => [ 
     0 => [ 
      'filter' => FILTER_VALIDATE_INT, 
      'default' => 1 
     ] 
    ],   
    '_page_title' => [ 
     0 => FILTER_SANITIZE_STRING, 
    ], 
    '_posts_title' => [ 
     0 => FILTER_SANITIZE_STRING, 
    ], 
    '_order_by' => [ 
     0 => [ 
      'filter' => FILTER_SANITIZE_STRING, 
      'default' => 'date' 
     ] 
    ], 
    '_asc' => [ 
     0 => [ 
      'filter' => FILTER_SANITIZE_STRING, 
      'default' => 'DESC' 
     ] 
    ], 
    '_post_count' => [ 
     0 => [ 
      'filter' => FILTER_VALIDATE_INT, 
      'default' => get_option('posts_per_page') 
     ] 
    ] 
]; 
$meta = filter_var_array($post_meta, $args); 

,但我從var_export($meta)

array (
    '_cat_id' => false, 
    '_page_title' => NULL, 
    '_posts_title' => NULL, 
    '_order_by' => false, 
    '_asc' => false, 
    '_post_count' => false, 
) 

東西得到下面的結果像_cat_id應該得到的數組中返回類似

'_cat_id' => 
    array (
    0 => 21, 
), 

如何多維數組上使用filter_var_array任何想法

+1

或許這可以幫助?看起來像filter_var_array不能遞歸工作。 http://stackoverflow.com/questions/4829355/filter-var-array-multidimensional-array – eol

回答

1

,你可以先「UNNEST」你的陣列$ post_meta,通過彈出的元素了每個子陣列使用array_maparray_pop的:

$post_meta_flat = array_map('array_pop', $post_meta); 

這個數組$ post_meta_flat看起來就像這樣:

array (
    '_edit_last' => '1', 
    '_edit_lock' => '1451326767:1', 
    '_sidebar' => 'Kies Sidebar', 
    '_wp_page_template' => 'page-pop.php', 
    'custom_sidebar_per_page' => 'default', 
    '_cat_id' => '21', 
    '_order_by' => 'date', 
    '_asc' => 'DESC', 
    '_post_count' => '5', 
    '_days' => '0', 
    '_custom_sidebar_per_page' => 'default', 
) 

而現在這應該工作:

$meta = filter_var_array($post_meta_flat, $args); 

當然,你可以兩者都做在一個班輪:

$meta = filter_var_array(array_map('array_pop', $post_meta), $args);