dongtanzhu5417 2016-10-19 02:52 采纳率: 100%
浏览 31

使用一维数组,将其展开,并创建一个多维数组

So I have an array that looks like this:

Array
 (
  [0] => john.smith@domain.com:John
  [1] => jane.doe@domain.com:Jane
)

As you can see, it's user'semail and user's name, seperated by a colon.

I want to create a multi dimensional array, that explodes the colon, and then will create a multi dimensional array that would look more like

Array
 (
   [0] => Array
    (
        [user_email] => john.smith@domain.com
        [user_name] => John
    )

   [1] => Array
    (
        [user_email] => jane.doe@domain.com
        [user_name] => Jane
    )

)
  • 写回答

2条回答 默认 最新

  • duanpuqi9965 2016-10-19 03:04
    关注

    You can do it like:

    <?php
    
    $data = [
        "john.smith@domain.com:John",
        "jane.doe@domain.com:Jane"
    ];
    
    function customArray($data){
        $final = [];
        $i = 0;
    
        foreach($data as $k => $v){
            $splitted = explode(":",$v);
            $final[$i]['user_email'] = $splitted[0];
            $final[$i]['user_name']  = $splitted[1];
            $i++;
        }
    
        return $final;
    }
    
    print_r(customArray($data));
    

    See the results here. Basically what I do above is

    • iterate over the array,
    • explode the value by the delimiter :,
    • index them within the iteration using the same [$i] so that the new key/value is paired correctly per original array element.

    Do properly name things though, I'm just giving an example :-)

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向