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 C++ /QT 内存权限的判断函数列举
  • ¥15 深度学习GFnet理解问题
  • ¥15 单细胞小提琴堆叠图代码
  • ¥80 LS dyna mpp并行报错
  • ¥50 升级strust2版本到2.3.15.1后使用ognl3.0.6.jar windows环境中没有问题,但部署到linux环境报错
  • ¥15 vue页面,node封装接口
  • ¥15 求TMS320F280039C工程模板!
  • ¥15 delphi+fastreport实现分组补空打印问题
  • ¥15 使用python把两台mysql数据库服务器数据导出和导入
  • ¥15 NodeBB论坛配置Apache Solr中文搜索引擎的详细教程