开发者

convert sub-arrays with only one value to a string

I have a multidimensional array, the sub-a开发者_开发知识库rrays consist of further values, I would like for all sub-arrays that only have one value to be converted into a string. How can I successfully scan through a multidimensional array to get the result?

Below is a small section of the array as it is now.

[1] => Array
(
    [name] => Array
        (
            [0] => Person's name
        )

    [organisation] => Array
        (
            [0] => This is their organisation
            [1] => aka something else
        )

    [address] => Array
        (
            [0] => The street name
            [1] => The town name
        )

    [e-mail] => Array
        (
            [0] => test@this.site.com
        )

)

and here is how I would like it to end up

[1] => Array
(
    [name] =>  Person's name

    [organisation] => Array
        (
            [0] => This is their organisation
            [1] => aka something else
        )

    [address] => Array
        (
            [0] => The street name
            [1] => The town name
        )

    [e-mail] => test@this.site.com

)


This should do the trick.

function array2string(&$v){
    if(is_array($v) && count($v)==1){
        $v = $v[0];
    }
}
array_walk($array, 'array2string');

Or as a one-liner, since I'm nuts.

array_walk($array, create_function('&$v', 'if(is_array($v) && count($v)==1){$v = $v[0];}'));

EDIT: It looks like that array is an element in a bigger array. You need to put this function inside of a foreach loop.

function array2string(&$v){
    if(is_array($v) && count($v)==1){
        $v = $v[0];
    }
}
foreach($array as &$val){
    array_walk($val, 'array2string');
}

Or using my crazy create_function one-liner.

foreach($array as &$val){
    array_walk($val, create_function('&$v', 'if(is_array($v) && count($v)==1){$v = $v[0];}'));
}


This should work no matter how deep the array is.

Put this function in your code:

function array2string(&$v){
    if(is_array($v)){
        if(count($v, COUNT_RECURSIVE) == 1){
            $v = $v[0];
            return;
        }
        array_walk($v, 'array2string');
    }
}

Then do this:

array_walk($array, 'array2string');


This PHP 5.3 code uses a closure. You can use a named function, too, if you want. It specifically checks for strings, and calls itself for nested arrays.

<?php
array_walk($array, $walker = function (&$value, $key) use (&$walker) {
    if (is_array($value)) {
        if (count($value) === 1 && is_string($value[0])) {
            $value = $value[0];
        } else {
            array_walk($value, $walker);
        }       
    }   
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜