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

报告相同问题?

悬赏问题

  • ¥20 qt中connect两个signal
  • ¥20 pix2pixHD运行测试命令时出现数据类型错误无法反向传播的问题
  • ¥15 python处理Excel符合条件的行自动填写数据分类
  • ¥15 汇编hook举例并讲解(通俗易懂,学习用)
  • ¥20 用c++语言模拟键盘电子琴设计
  • ¥15 STM32cubemx生成keil工程,有问题与正常的情况不同,求解!
  • ¥15 如何自动点击银行app的安全键盘,实现密码自动输入
  • ¥15 关于四边形重叠的问题
  • ¥15 用verilog语言设计一个简易的八音符电子琴,可通过按键输入来控制音响。演奏时可以选择是手演奏(由键盘输入)或自动演奏已存入的乐曲。能够自动演奏多首乐曲,且每首乐曲可重复演奏
  • ¥15 sap gui脚本每次到导出Excel的时候就停住不动。不会另存为。