convert sub-arrays with only one value to a string

梦想与她 提交于 2019-12-25 13:14:47

问题


I have a multidimensional array, the sub-arrays 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

)

回答1:


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');



回答2:


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];}'));
}



回答3:


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);
        }       
    }   
});


来源:https://stackoverflow.com/questions/3569734/convert-sub-arrays-with-only-one-value-to-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!