迭代数组并获取键和值

时间:2010-09-20 16:21:30

标签: php arrays iteration

我需要遍历动态数组。该数组将如下所示:

Array
(
    [2010091907] => Array
        (
            [home] => Array
            (
                [score] => Array
                (
                        [1] => 7
                        [2] => 17
                        [3] => 10
                        [4] => 7
                        [5] => 0
                        [T] => 41
                    )

                [abbr] => ATL
                [to] => 2
            )

        [away] => Array
            (
                [score] => Array
                    (
                        [1] => 0
                        [2] => 7
                        [3] => 0
                        [4] => 0
                        [5] => 0
                        [T] => 7
                    )

                [abbr] => ARZ
                [to] => 2
            )

        [weather] => 
        [media] => Array
            (
                [tv] => FOX
                [sat] => 709
                [sathd] => 709
                [radio] => Array
                    (
                        [home] => 153
                        [away] => 90
                    )

            )

        [bp] => 13
        [yl] => 
        [qtr] => Final
        [down] => 0
        [togo] => 0
        [clock] => 00:26
        [posteam] => ARZ
        [note] => 
        [redzone] => 
        [stadium] => Georgia Dome
    )

我需要它是动态的并且出于测试目的,我需要能够通过以下方式调用它:

echo "Key: $key; Value: $value<br />\n";

我稍后会把这些信息放到一个mysql数据库中,但是现在,我需要刷新数组并弄清楚如何格式化数据。

感谢任何帮助。

1 个答案:

答案 0 :(得分:21)

我会去一个递归函数:如果一个值是一个数组,再次调用它,否则显示键/值对。

像(未经测试)的东西:

function display_array($your_array)
{
    foreach ($your_array as $key => $value)
    {
        if is_array($value)
        {
            display_array($value);
        }
        else
        {
             echo "Key: $key; Value: $value<br />\n";
        }
    }
}

display_array($some_array);