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条)

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错