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

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改