I am trying to remove all spaces in array keys names i.e. str_replace(\' \',\'\',$value) (or worst cast scenario replace them with underscores (_) )
and I am trying
function array_stripstuff(&$elem)
{
if (is_array($elem)) {
foreach ($elem as $key=>$value)
$elem[str_replace(" ","-",$key)]=$value;
}
return $elem;
}
$strippedarray = array_walk_recursive($yourarray,'array_stripstuff');
There you go :-)
This will help:
function fixArrayKey(&$arr)
{
$arr = array_combine(
array_map(
function ($str) {
return str_replace(" ", "_", $str);
},
array_keys($arr)
),
array_values($arr)
);
foreach ($arr as $key => $val) {
if (is_array($val)) {
fixArrayKey($arr[$key]);
}
}
}
Tested as below:
$data = array (
"key 1" => "abc",
"key 2" => array ("sub 1" => "abc", "sub 2" => "def"),
"key 3" => "ghi"
);
print_r($data);
fixArrayKey($data);
print_r($data);
Input:
Array
(
[key 1] => abc
[key 2] => Array
(
[sub 1] => abc
[sub 2] => def
)
[key 3] => ghi
)
Output:
Array
(
[key_1] => abc
[key_2] => Array
(
[sub_1] => abc
[sub_2] => def
)
[key_3] => ghi
)
You can pass an array to str_replace
so it's much cleaner and easier to just do this:
$my_array = array( 'one 1' => '1', 'two 2' => '2' );
$keys = str_replace( ' ', '', array_keys( $my_array ) );
$results = array_combine( $keys, array_values( $my_array ) );
Result:
array(2) {
["one1"]=>
string(1) "1"
["two2"]=>
string(1) "2"
}
Example: https://glot.io/snippets/ejej1chzg3