filter_input_array在多维数组上

时间:2016-02-02 19:04:58

标签: php arrays multidimensional-array filter-var

我来自var_export( $post_meta );的{​​{1}}的结果中包含以下数组;

$post_meta = get_post_meta( 80 )

现在我需要过滤一些这些值,如果它们存在,那么我可以安全地使用它们。我做了以下

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, ), 的任何想法

1 个答案:

答案 0 :(得分:1)

你可以先"不要"您的数组 $ 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 );