使用基本的关联数组,如:
$ar = array("First" => 1, "Second" , "Third" =>"Three");
如果你这样做:
foreach($ar as $key => $val) {
var_dump($key);
}
这将产生:
string 'First' (length=5)
int 0
string 'Third' (length=5)
如何在多维数组中获得相同的结果?
类似的东西:
array( 0 => array(
"First" => 1, "Two", "Third" => "Three"
)
);
我试过了:
foreach($ar as $k => $v){
var_dump($ar[0][$k]);
}
我得到了:
string 'Two' (length=3)
而不是:
string 'First' (length=5)
int 0
string 'Third' (length=5)
感谢名单
答案 0 :(得分:2)
如果$ ar等于:
array( 0 => array(
"First" => 1, "Two", "Third" => "Three"
)
);
您可以迭代内部数组以获得相同的结果:
foreach ($ar as $k => $v) {
foreach ($v as $k2 => $v2) {
var_dump($k2);
}
}
输出:
string(5) "First"
int(0)
string(5) "Third"
答案 1 :(得分:2)
function get_key(&$arr){
foreach($arr as $key=>$value){
if(is_array($value)){
get_key($value);
}else{
var_dump($key);
}
}
}
$arr = array(
'key1'=>array('a'=>1,'b'=>2),
'key2'=>array('c'=>1,2),
);
get_key($arr);
输出:
string(1) "a"
string(1) "b"
string(1) "c"
int(0)
答案 2 :(得分:1)
您可以像这样迭代内部数组的值:
foreach($ar[0] as $k => $v){
var_dump($v);
}
你的问题是你只是在ar数组中循环遍历1个元素,然后将该数字应用于其中的数组。
如果你也想在两个级别上做同样的事情,你需要另一个foreach循环:
foreach($ar as $k => $v){
foreach($v as $k => $n){
var_dump($n);
}
}
答案 3 :(得分:1)
您可以访问多维数组键和索引,如下所示:
$ary = array('whatever' => array('First' => 1, 'Two', 'Third' => 'Three'),
array('something' => array('cool' => 'yes', 'awesome' => 'super', 'great' => 10)
);
foreach($ary as $k => $a){
// $k is each Array key within initial Array
foreach($a as $i => $v){
// $i is internal index
// $v is internal value
}
}
注意:
在包含Arrays的Array中,第一个Array实际上是键0下的值,除非将Array分配给键,因此不需要键0。
答案 4 :(得分:1)
$arr = array(
0 => array("First" => 1, "Two", "Third" => "Three")
);
foreach ($arr as $key => $value)
{
foreach ($value as $k => $v)
{
var_dump($k);
}
}