在php中的多维数组中列出值 [英] List values in multi-dimensional array in php

查看:289
本文介绍了在php中的多维数组中列出值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了一段时间了.我看到php中的多维数组不是那么容易.这是我的代码:

I have been working on this a while. I see multi-dimensional arrays in php are not that easy. Here is my code:

      while (list($key,$value) = each ($x))
        {
        Print "$key  => $value\n<br>\n";
        }

这很好地显示了主数组的键.我得到的是:

This works well to display the keys of the main array. what I get is :

visitors => Array 
actions => Array 
actions-average => Array 
time-average => Array 
pages-entrance => Array

我想要的是访问者以及值(访问者数量),操作值等.然后,我想将值保存在Mysql中.有些我将不得不从字符串转换为int或date.

What I want is the visitors and the value (number of visitors), value of actions, etc. I want to then save the value in Mysql. Some I will have to convert from a string to and int or date.

我需要再列出一个层次.但是我看不到该怎么做.- - - - - - - 添加 - - - - - -所以我所拥有的是一个数组数组.我需要逐步遍历每个数组.

I need to list one more level deep. But I cannot see how to do this. --------------Added ----------- So what I have is an array of arrays. I need to step through each array.

推荐答案

您尝试 print_r 吗?

如果您需要对格式进行更多控制,那么@Nick建议的嵌入式循环是最好的选择.尽管使用foreach循环比使用循环更自然,更安全.

if you need more control over formatting then embedded loops as suggested by @Nick is the best option. Although it would be more natural and safer to use foreach loops rather than while.

foreach($x as $key => $value){
  foreach( $value as $key2 => $value2){
    print "$key $key2 => $value2\n<br />\n";
  }
}

请参见 PHP手册:每本,其中都有一个警告"框.

see PHP manual: each , there is a "caution" frame.

编辑1 我将上面的示例代码更新为2天的阵列.

似乎您的数组有2维以上.然后,您应该使用递归.

It seems your array has more than 2 dimension. Then you should use recursion.

function my_print_r($x,$header="")
{
  foreach($x as $key => $value){
    if(is_array($value))
      my_print_r($value,$header . $key .  " " );
    else
      print "$header $key2 => $value2\n<br />\n";
  }
}

这篇关于在php中的多维数组中列出值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆