php 遍历数组并获取键和值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3753394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate through array and get key and value
提问by drewrockshard
I need to iterate through a dynamic array. The array will look something like the following:
我需要遍历动态数组。该数组将类似于以下内容:
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
)
I need it to be dynamic and for testing purposes, I need to be able to call it via:
我需要它是动态的,为了测试目的,我需要能够通过以下方式调用它:
echo "Key: $key; Value: $value<br />\n";
echo "Key: $key; Value: $value<br />\n";
I'm going to later take this information and place it into a mysql database, but for now, I need to brush up on arrays and figure out how to format the data.
稍后我将获取这些信息并将其放入 mysql 数据库中,但现在,我需要复习数组并弄清楚如何格式化数据。
Any help is appreciated.
任何帮助表示赞赏。
回答by jeroen
I′d go for a recursive function: If a value is an array, call it again and otherwise display the key / value pair.
我会使用递归函数:如果一个值是一个数组,则再次调用它,否则显示键/值对。
Something like (not tested):
类似的东西(未测试):
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);