简体   繁体   中英

Strip whitespace from associative array Keys

I have an associative that outputs whitespace in the key and value. I need to strip the whitespace from first letter and also the last letter and keep the space inbetween.

I have tried

$stripResults = array_filter(array_map('trim', $results));

This strips the value perfectly but not the key. How do I strip the key and value?

Keys must be processed separately:

$a = array_map('trim', array_keys($stripResults));
$b = array_map('trim', $stripResults);
$stripResults = array_combine($a, $b);

Try this function will help you..

function trimArrayKey(&$array)
{
    $array = array_combine(
        array_map(
            function ($str) {
                return str_replace(" ", "_", $str);
            },
            array_keys($array)
        ),
        array_values($array)
    );

    foreach ($array as $key => $val) {
        if (is_array($val)) {
            trimArrayKey($array[$key]);
        }
    }
}

Hope this helps...

If you're looking at this and need to remove or replace spaces that are not at beginning or end of key, you can pass an array to str_replace :

$my_array = array( 'one 1' => '1', 'two 2' => '2' );
$keys = str_replace( ' ', '', array_keys( $my_array ) );
$results = array_combine( $keys, array_values( $my_array ) );

Example: https://glot.io/snippets/ejej1chzg3

The accepted answer didn't solve the problem for my particular scenario, but this did the trick.

$temp = array();
foreach ($stripResults as $key => $value) {
    $temp[trim($key)] = trim($value);
}
$stripResults = $temp;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM