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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度