迭代嵌套数组和转义值

时间:2015-09-01 10:20:51

标签: php arrays wordpress

我有一个WordPress项目,它在数据库中存储一组值,在我存储数组之前,我想要转义包含HTML的值,以便只允许标记由WordPress存储到DB

数组内容如下所示:

Array
(
    [demo_radio] => Array
        (
            [black] => two
            [green] => one
            [blue] => two
            [purple] => one
            [yellow] => two
            [orange] => one
            [red] => two
            [gray] => one
        )

    [demo_slider_black] => 4000,400
    [demo_slider_two_black] => 810
    [demo_slider_green] => 700,1000
    [demo_slider_two_green] => 840
    [demo_slider_blue] => 7900,8600
    [demo_slider_two_blue] => 10
    [demo_slider_purple] => 900,9600
    [demo_slider_two_purple] => 10
    [demo_slider_yellow] => 8100,800
    [demo_slider_two_yellow] => 170
    [demo_slider_orange] => 900,9300
    [demo_slider_two_orange] => 20
    [demo_slider_red] => 800,900
    [demo_slider_two_red] => 50
    [demo_slider_gray] => 1800,3500
    [demo_slider_two_gray] => 270
    [text_area] => This is the contents. Do you like <b>them</b> ?
    [panels_info] => Array
        (
            [class] => Test_Widget
            [raw] => 1
            [grid] => 0
            [cell] => 0
            [id] => 0
            [style] => Array
                (
                    [class] => 
                    [widget_css] => 
                    [padding] => 
                    [background] => 
                    [background_image_attachment] => 0
                    [background_display] => tile
                    [border_color] => 
                    [font_color] => 
                    [animation_type] => bounce
                    [animation_delay] => 
                )

        )

)

我已经设置了这个iterrator:

$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator( $new ));

foreach($iterator as $key=>$value) {
    echo $key . ' -- ' . $value . "\r\n";
}

迭代所有值,但我喜欢做的是更新等效值,因此对我的数据库来说是安全的。

那么,通过使用这个迭代器,是否可以更新数组值?

更新#1

所以我解决了我的问题,并与您分享我未来使用其他成员的解决方案。

消化@Rizier123后,我的代码如下:

// Other class code here
...
public function update($new, $old) {
    array_walk_recursive( $new, array( $this, 'esc_values' ) );
}

public function esc_values( &$item, $key ) {

    if ( preg_match( '/\<[a-zA-Z]+[^\>]*\>([^\<]*\<\/[a-zA-Z]+\>)?/', $item ) ) {
        $item = wp_kses_post( $item );
    }
}

并且完美无缺。

0 个答案:

没有答案