简体   繁体   中英

How to replace curly bracket in PHP encoded array value

I have a string in encoded array format. What I want is to replace the curly bracket in its value only. I have tried like this

$str = '[{"id":"{3e71209}","elType":"section","settings":[],"elements":[{"id":"70e5fb7","elType":"column","settings":{"_column_size":100,"_inline_size":null},"elements":[{"id":"70e09a1","elType":"widget","settings":{"title":"{title1|title2|title3}"},"elements":[],"widgetType":"heading"}],"isInner":false}],"isInner":false}]';
echo 'str asli: '.$str;
echo '<br><br>';


$strOlah = str_replace("{", "xx", json_decode($str));

echo 'str olah: '. json_encode($strOlah);

it's resulting the exact str. nothing change. My expected result is the str become like this

[{"id":"xx3e71209}","elType":"section","settings":[],"elements":[{"id":"70e5fb7","elType":"column","settings":{"_column_size":100,"_inline_size":null},"elements":[{"id":"70e09a1","elType":"widget","settings":{"title":"xxtitle1|title2|title3}"},"elements":[],"widgetType":"heading"}],"isInner":false}],"isInner":false}]

How to do that without looping through an array because the structure and key of the array are very dynamic.

You need to loop through the array, calling str_replace() on the specific object properties.

$array = json_decode($str);
foreach ($array as $obj) {
    $obj->id = str_replace("{", "xx", $obj->id);
    foreach ($obj->elements as $el1) {
        foreach ($el1->elements as $el2) {
            $el2->settings->title = str_replace("{", "xx", $el2->settings->title);
        }
    }
}
echo 'str olah: ' . json_encode($array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM