dongzhan1492 2017-07-25 14:53
浏览 27
已采纳

如何在PHP中从现有的多维数组创建新数组

I have the following multi-dimensional array (this is only an extract) and would like to dynamically create a set of one-dimensional arrays and add values.

What I have:

0 => 
     0 => Image
     1 => DE
     2 => Hamburg-S02-I01
     3 => 54
     4 => Button
1 => 
     0 => Image
     1 => GB
     2 => London-S01-I01
     3 => 51
     4 => Button
2 => 
     0 => Image
     1 => GB
     2 => London-S01-I04
     3 => 60
     4 => Button
3 => 
     0 => Image
     1 => DE
     2 => Berlin-S02-I01
     3 => 57
     4 => Button
4 => 
     0 => Image
     1 => DE
     2 => Hamburg-S02-I01
     3 => 52
     4 => Button

What I need:

$Hamburg = array('Hamburg-S02-I01', 'Hamburg-S02-I01');
$London= array('London-S01-I01', 'London-S01-I04');
$Berlin= array('Berlin-S02-I01');

I appreciate your help! Thanks!

  • 写回答

3条回答 默认 最新

  • douji9518 2017-07-25 15:09
    关注
    $new_array = array();
    foreach ($array as $key => $val) {
        $new_array[explode('-',$val[2])[0]][] = $val;
    }
    

    That code travels through your array - that I arbitrarily named $array - and push every sub_array in it inside sub_arrays in another array which key will be whatever is before the first hyphen character in the third entry of the original sub_array. I don't know if it's what you were after, but maybe at least it will inspire you.

    Content of new array : (3) [Hamburg] => (2) [0] => (5) [0] => Image [1] => DE [2] => Hamburg-S02-I01 [3] => 54 [4] => Button [1] => (5) [0] => Image [1] => DE [2] => Hamburg-S02-I01 [3] => 52 [4] => Button [London] => (2) [0] => (5) [0] => Image [1] => GB [2] => London-S01-I01 [3] => 51 [4] => Button [1] => (5) [0] => Image [1] => GB [2] => London-S01-I04 [3] => 60 [4] => Button [Berlin] => (1) [0] => (5) [0] => Image [1] => DE [2] => Berlin-S02-I01 [3] => 57 [4] => Button

    $new_array = array();
    foreach ($array as $key => $val) {
        $new_array[explode('-',$val[2])[0]][] = $val[2];
    }
    

    The second version pushes only the third entry, since it seems that's what you're after.

    Output : (3) [Hamburg] => (2) [0] => Hamburg-S02-I01 [1] => Hamburg-S02-I01 [London] => (2) [0] => London-S01-I01 [1] => London-S01-I04 [Berlin] => (1) [0] => Berlin-S02-I01

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵