Home > Software engineering >  Remove space before and after string in array and keep structure
Remove space before and after string in array and keep structure

Time:08-12

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"

CodePudding user response:

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);

CodePudding user response:

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

$data = json_decode($json, true);
$data = array_filter($data);

Like this you use instead of foreach.

or either use

trim(); // Function
  •  Tags:  
  • php
  • Related