How to remove spaces in array keys names in php?

前端 未结 3 2020
你的背包
你的背包 2020-12-20 02:08

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

相关标签:
3条回答
  • 2020-12-20 02:34
    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 :-)

    0 讨论(0)
  • 2020-12-20 02:40

    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
    )
    
    0 讨论(0)
  • 2020-12-20 02:49

    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

    0 讨论(0)
提交回复
热议问题