douxiong1994 2017-05-01 07:47
浏览 6
已采纳

我可以将这种格式的数组拆分成这个吗?

How can I do the below change in PHP?

Input:

[hiddenAllPrefered] => Array
(
    [0] => 14477,14478,14479,14485,14486,14487
)

Output should be like this:

[hiddenAllPrefered] => Array
(
    [0] => 14477,14478,14479
    [1] => 14485,14486,14487
)
  • 写回答

2条回答 默认 最新

  • dongqiao1151 2017-05-01 08:11
    关注

    A possible solution:

    $input = array('14477,14478,14479,14485,14486,14487');
    
    $output = array_map(
        function (array $a){
            return implode(',', $a);
        },
        array_chunk(
            explode(',', $input[0]),
            3
        )
    );
    

    Read it from inside out:

    • explode() splits the string $input[0] using comma (,) as delimiter and returns an array;
    • array_chunk() splits the array into chunks of size 3; it returns an array of arrays, each inner array contains 3 elements (apart from the last one that can contain less);
    • array_map() applies the function it receives as its first argument to each value of the array it gets as its second argument (the array of arrays returned by array_chunk()); it returns an array whose values are the values returned by the function;
    • the anonymous function passed to array_map() gets an array (of size 3 or less) and uses implode() to join its elements into a string, using comma (,) to separate the values and returns the string;
    • array_map() puts together all the values returned by the anonymous function (one for each chunk of 3 elements of the array) into a new array it returns.

    The output (print_r($output)) looks like this:

    Array
    (
        [0] => 14477,14478,14479
        [1] => 14485,14486,14487
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?