douxing2156 2017-12-05 16:01
浏览 56
已采纳

php - 将数组转换为数组

I have an array like below:

array:3 [▼
  "_token" => "hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso"
  "room_id" => array:3 [▼
    0 => "089a6ca8-26de-3ca2-bbbf-17c410d15266"
    1 => "13c56ac2-6c77-3ca7-b24a-2a70f4f0526c"
    2 => "2d9b7392-aa50-37e4-882a-804affb87223"
  ]
  "new_electric" => array:3 [▼
    0 => "123"
    1 => "234"
    2 => "345"
  ]
]

How can I slice it into new array which like

array:4 [▼
  "_token" => "hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso"
  "1" => array:2 [▼
    "room_d" => "089a6ca8-26de-3ca2-bbbf-17c410d15266"
    "new_electric => "123"
  ]
  "2" => array:2 [▼
    "room_id" => "13c56ac2-6c77-3ca7-b24a-2a70f4f0526c"
    "new_electric" => "234"
  ]
  "3" => array:2 [▼
    "room_id" => "2d9b7392-aa50-37e4-882a-804affb87223"
    "new_electric" => "345"
      ]
]

I think I need to use an array_push but I don't know how to do that ? Please help.

  • 写回答

3条回答 默认 最新

  • duanjiong1952 2017-12-05 16:09
    关注

    You have to use foreach

    $arr = array(
          "_token" => "hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso",
          "room_id" => array(
            0 => "089a6ca8-26de-3ca2-bbbf-17c410d15266",
            1 => "13c56ac2-6c77-3ca7-b24a-2a70f4f0526c",
            2 => "2d9b7392-aa50-37e4-882a-804affb87223",
          ),
          "new_electric" => array(
            0 => "123",
            1 => "234",
            2 => "345",
          )
        );
    
        $final = array();
        $final[ "_token" ] = $arr[ "_token" ];
    
        foreach( $arr[ "room_id" ] as $key => $value ) {
    
            $final[ ( $key + 1 ) ] = array(
                "room_id" => $value,
                "new_electric" => $arr[ "new_electric" ][ $key ]
            );
    
        }
    

    This will result to:

       Array
    (
        [_token] => hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso
        [1] => Array
            (
                [room_id] => 089a6ca8-26de-3ca2-bbbf-17c410d15266
                [new_electric] => 123
            )
    
        [2] => Array
            (
                [room_id] => 13c56ac2-6c77-3ca7-b24a-2a70f4f0526c
                [new_electric] => 234
            )
    
        [3] => Array
            (
                [room_id] => 2d9b7392-aa50-37e4-882a-804affb87223
                [new_electric] => 345
            )
    
    )
    

    Note: Use $key + 1 because you want the index to start from 1

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?