dongzhao2725 2016-07-25 23:17
浏览 44
已采纳

当每个键都是一个字符串时,迭代PHP中的多维关联数组

I've got an array like:

$fruits = array(
  'citrus' => array(
    'fruit one' => 'orange',
    'fruit two' => 'lime',
  ),
  'melon' => array(
    'fruit one' => 'honeydew',
    'fruit two' => 'cantalope',
  ),
  'berry' => array(
    'fruit one' => 'raspberry',
    'fruit two' => 'strawberry',
  ),
  'apple' => array(
    'fruit one' => 'granny smith',
    'fruit two' => 'fuji',
  )

);

I want to be able to access slices of it, like echo $fruits[0]['fruit one']; so that I can create a for loop to get at specific groups of the array. By that I mean, I would ideally be able to do something like:

for($i = 0; $i <= 1; $i++)
  echo $fruit[$i]['fruit one'];

// Then some other code

for($i = 2; $i <= 3; $i++)
  echo $fruit[$i]['fruit one'];

Of course I can't do that since every key is a string. Is there a simple solution to this or did I just code this dumbly?

Edit: I made the array longer to fully demonstrate what I'm trying to do.

  • 写回答

3条回答 默认 最新

  • dqs13465424392 2016-07-25 23:53
    关注

    array_slice (docs) was made just for this.

    For the first 2 fruit groups:

    foreach(array_slice($fruits,0,2) as $fruitGroup) echo $fruitGroup['fruit one'];
    

    For the next 2 fruit groups:

    foreach(array_slice($fruits,2,2) as $fruitGroup) echo $fruitGroup['fruit one'];
    

    Live demo

    This has the benefit of simplicity (over Chrys' solution), and of not destroying the original keys from your array.

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

报告相同问题?

悬赏问题

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