How to search and replace value in multidimensional array in php
we implement following code for search and replace a value in multidimensional array without loops like (while, for, for each) so this is very fast when compared to others.
<?php
$data = array(
'repeater-1' => array(
array(
'first_value' => 'value1',
'second_value' => 'value2',
),
array(
'first_value' => 'value3',
'second_value' => 'value4',
),
),
'repeater-2' => array(
array(
'first_value' => 'value5',
'second_value' => 'value6',
),
array(
'first_value' => 'value7',
'second_value' => 'value8',
),
),
);
$stu_bridge_json = str_replace_json('value1','my_value',$data);
//convert array to json and replace a string and create back to array
function str_replace_json($search, $replace, $subject){
return json_decode(str_replace($search, $replace, json_encode($subject)));
}
Output
stdClass Object
(
[repeater-1] => Array
(
[0] => stdClass Object
(
[first_value] => my_value
[second_value] => value2
)
[1] => stdClass Object
(
[first_value] => value3
[second_value] => value4
)
)
[repeater-2] => Array
(
[0] => stdClass Object
(
[first_value] => value5
[second_value] => value6
)
[1] => stdClass Object
(
[first_value] => value7
[second_value] => value8
)
)
)
No comments: