3

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 to do this at the deepest level (shown below) of my multidimensional array (because other layers/levels don't have spaces (THANK GOD!))

[...]

[ownPagestoriesbystorytype] => Array
                        (
                            [type] => pagestoriesbystorytype
                            [object_id] => 12365478954
                            [metric] => page_stories_by_story_type
                            [end_time] => 1386057600
                            [period] => 86400
                            [ownValues] => Array
                                (
                                    [type] => pagestoriesbystorytypemetrics
                                    [fan] => 1913
                                    [page post] => 153
                                    [user post] => 24
                                )

                        )

                    [ownPagestorytellersbystorytype] => Array
                        (
                            [type] => pagestorytellersbystorytype
                            [object_id] => 12365478954
                            [metric] => page_storytellers_by_story_type
                            [end_time] => 1386057600
                            [period] => 86400
                            [ownValues] => Array
                                (
                                    [type] => pagestorytellersbystorytypemetrics
                                    [fan] => 1902
                                    [page post] => 137
                                    [user post] => 9
                                )

                        )

[...]

So far my attempts have been fruitless :

[...]
if (is_array($value))
        {

            $keys = str_replace(' ','',array_keys($value));
            $values = array_values($value);
            $value = array_combine($keys,$values);
        }
[...]


[...]

foreach ($value as $k => $v)
            {
                $b = str_replace(' ','',$k);
                $value[$b] = $value[$k];
                unset ($value[$k]);

            }

[...]

The codes above do not work, however if I put print_r($value); at the end of the loop you can clearly see that spaces are being removed, just somehow the end result ends up being with spaces (STILL).

The whole loop looks like this:

for ($i=0;$i<count($results);$i++)
{

    for ($j=0;$j<count($results[$i]);$j++)
    {
    foreach($results[$i][$j] as $key => $value)
    {
        $typee = ['type' => strtolower(str_replace('_','',$results[$i][$j]['metric']))];
        array_insert($results[$i][$j],$typee,0);
        if (is_array($value))
        {

            $keys = str_replace(' ','',array_keys($value));
            $values = array_values($value);
            $value = array_combine($keys,$values);

            $type = ['type' => strtolower(str_replace('_','',$results[$i][$j]['metric']))."metrics"];
            array_insert($results[$i][$j]['value'],$type,0);
            $results[$i][$j]['ownValues'] = $results[$i][$j][$key];
            unset($results[$i][$j][$key]);


        }
    }
    }
}

And you can see how the whole array looks like here:

How to prepend array to each element of another array with my choice of key and value (in php)?

Any suggestions? :)

3 Answers 3

9

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
)
Sign up to request clarification or add additional context in comments.

4 Comments

Hey, would you also know how to remove all special characters like "á", "ü" etc. If I add them like this, it doesnt work :((( => function fixArrayKey(&$arr) { $arr=array_combine(array_map(function($str){return str_replace(array(" ",",",".","-","+","á","я", "Я"),"",$str);},array_keys($arr)),array_values($arr)); foreach($arr as $key=>$val) { if(is_array($val)) fixArrayKey($arr[$key]); } }
I mean all of these [",",",".","-","+"] work perfectly fine and are being replaced, its just special characters (foreign) are not working.. would you know why?
great it work with every kind of array
6

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

3 Comments

What do you mean? You want to exclude removing spaces on custom defined keys, but replace them on all others?
Yes, you are write. just exclude some specific key name that we want to exclude in special condition.
@LimSocheat unset first?
1
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 :-)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.