Replace text inside a huge multidimensional array

I’ve a huge multidimensional array with no-way to foreach it :), Anyway, i want to replace all http to a keyword so if the client convert his website into https he won’t change all old images for the new url.

I tried array_map, array_walk and of course str_replace but i found that i must make infinite foreach for every nested array.

Array (

[Repeater_1] => Array (

        [1] => Array (
                [user_defined_field_1] => http://Value_1
                [user_defined_field_2] => http://Value_2
            )

        [2] => Array (
                [user_defined_field_1] => http://Value_1
                [user_defined_field_2] => http://Value_2
            )

    )

[Repeater_2] => Array (

        [1] => Array (
                [user_defined_field_3] => http://Value_1
                [user_defined_field_4] => http://Value_2
            )

        [2] => Array (
                [user_defined_field_3] => http://Value_1
                [user_defined_field_4] => http://Value_2
            )
    )
)

1 Answer
1

Try this php built-in function array_walk_recursive

function wpse_do_something_on_data() {
   $data = array(
        'repeater-1' => array(
            array(
                'user_defined_field1' => 'http://www.domain-001.com',
                'user_defined_field2' => 'http://www.domain-002.com',
            ),

            array(
                'user_defined_field1' => 'http://www.domain-011.com',
                'user_defined_field2' => 'http://www.domain-012.com',
            ),
        ),

        'repeater-2' => array(
            array(
                'user_defined_field1' => 'http://www.domain-101.com',
                'user_defined_field2' => 'http://www.domain-102.com',
            ),

            array(
                'user_defined_field1' => 'http://www.domain-111.com',
                'user_defined_field2' => 'http://www.domain-112.com',
            ),
        ),
    );

   array_walk_recursive( $data, 'wpse_callback' );

   return $data;
}

function wpse_callback( &$value, $key ) {
   $value = str_replace( 'http://', 'keyword', $value );
}

$my_data = wpse_do_something_on_data();

var_dump( $my_data ); 

Leave a Comment