dsbiw2911188 2016-10-29 13:37
浏览 31
已采纳

拆分数组以创建关联数组

I have an array that looks like this:

a 12 34
b 12345
c 123456

So the array looks like

$array[0] = "a 12 34"
$array[1] = "b 12345"
$array[2] = "c 123456"

I am trying to create an associative array such that

[a] => 12 34
[b] => 12345
[c] => 123456

Can I possibly split the array into two, one for containing "a, b, c" and another for their contents and use the array_combine()? Or are there any other ways?

  • 写回答

3条回答 默认 最新

  • dongwei7048 2016-10-29 13:50
    关注

    You can do that within a loop like the snippet below demonstrates. Quick-Test here:

            $array      = array("a 12 34", "b 12345", "c 123456");
            $array2     = array();
    
            foreach($array  as $data){
                preg_match("#([a-z])(\s)(.*)#i", $data, $matches);
                list(, $key, $space, $value)    = $matches;
                $array2[$key]   = $value;
            }
    
            var_dump($array2);
            // YIELDS::
            array(3) {
                ["a"]=>  string(5) "12 34"
                ["b"]=>  string(5) "12345"
                ["c"]=>  string(6) "123456"
            }
    

    Or using a Blend of array_walk() and array_combine() which can be Quick-Tested Here.

            <?php
    
                $array      = array("a 12 34", "b 12345", "c 123456");
                $keys       = array();
    
                array_walk($array, function(&$data, $key) use (&$keys){
                    $keys[] = trim(preg_replace('#(\s.*)#i',   '', $data));;
                    $data   = trim(preg_replace('#(^[a-z])#i', '', $data));
                });
    
                $array = array_combine($keys, $array);
    
                var_dump($array);;
                // YIELDS::
                array(3) {
                    ["a"]=>  string(5) "12 34"
                    ["b"]=>  string(5) "12345"
                    ["c"]=>  string(6) "123456"
                }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP