1

I need to remove all space before string and keep space in string and remove all space after string in array and keep the structure of array

$data = json_decode($json, true);
foreach($data as $index => $value){
    $tables = json_encode($value["tables"], JSON_UNESCAPED_UNICODE);
    echo $tables;
}

Result from echo $tables;

[{"lang":"cs","lang_title":"Český","menus":[{"header":"Mechanika","rows":[{"parameter":"Hmotnost","value":"0.65kg"}]}]},{"lang":"pl","lang_title":"Polský","menus":[{"header":"Mechanika nová","rows":[{"parameter":"Masa","value":"0.65kg"}]}]},{"lang":"en","lang_title":"Anglický","menus":[{"header":" Me chanics ","rows":[{"parameter":"Weight","value":"0.65kg"}]}]}]

And I need to keep the structure of $value["tables"] and just remove spaces in header,parameter,value

So example "header":" Me chanics " -> "header":"Me chanics"

2
  • Iterate through all this and replace the values with their new value after "trim()". Commented Aug 12, 2022 at 9:01
  • Sorry, I am not sure if I understand, can you explain "Iterate through all this and replace the values" please? I don't know how you mean that. Commented Aug 12, 2022 at 9:08

2 Answers 2

1

You can use array_walk_recursive to walk through entire array and use trim to remove extra spaces

    $json = '[{"lang":"cs","lang_title":"Český ","menus":[{"header":"Mechanika","rows":[{"parameter":"Hmotnost","value":"0.65kg"}]}]},{"lang":"pl","lang_title":"Polský","menus":[{"header":"Mechanika nová","rows":[{"parameter":"Masa","value":"0.65kg"}]}]},{"lang":"en","lang_title":"Anglický","menus":[{"header":" Me chanics ","rows":[{"parameter":"Weight","value":"0.65kg"}]}]}]';
    
    
    $data = json_decode($json, true);
    array_walk_recursive(
            $data, function(&$v, $key) {
        if (in_array($key, ["header", "parameter", "value"]))
            $v = trim($v);
    }
    );
    
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
Sign up to request clarification or add additional context in comments.

1 Comment

It seems like my problem is fixed, thank you so much for your time and your willing.
1

What better you can do is after decoding the data into $data use array_map function

$data = json_decode($json, true);
$data = array_map('trim', $data);

Like this you use instead of foreach.

or either use

trim(); // Function

2 Comments

Okay, thank you, can I ask how to use this function array_filter() with trim()?
@AmeliaDernigue I here said to use array_filter() or either trim(). I don't think trim will be require if you use array_filter().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.