在foreach
我想访问数组值,数组看起来像这样。
Array
(
['name'] => John Doe
['age'] => 25
['from'] => Australia
)
如何获得name
age
和from
的价值?
使用echo $item['name']
并返回Undefined index: name
。
答案 0 :(得分:2)
如果您正在使用该数组进行预告,则只需要回显项目:
$the_array = array( 'name'=> "John Doe", 'age' => 25, 'from' => 'Oz');
foreach($the_array as $item){
//the first iterations will echo out $the_array['name'],
//second $the_array['age'], etc...
echo $item;
//in this loop $item['name'] has no meaning if that's what you're doing....
}
现在,如果它真的是一个数组数组,你可以这样做
$the_array = array(array( 'name'=> "John Doe", 'age' => 25, 'from' => 'Oz'));
foreach($the_array as $item){
foreach($item as $key=>$value){
echo $key." ".$value;
}
}
如果您没有肯定要设置回显的值,但不想要内循环:
foreach($the_array as $item){
$name =isset($item['name']) ?$item['name'] : null;
echo $name;
$age =isset($item['age']) ?$item['age'] : null;
echo $age;
//...etc...
}