Array
(
[0] => Array
(
[0] => 1
)
[1] => Array
(
[0] => 2
)
[2] => Array
(
[0] => 3
)
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
[8] =>
[9] =>
[10] =>
[11] =>
[12] =>
[13] =>
[14] =>
)
如何使用foreach打印上面的数组?我尝试使用这样的foreach:
$i = 0;
foreach($array as $arr)
{
echo $arr[$i];
$i++;
}
但结果是空的。
答案 0 :(得分:1)
如果值本身是一个数组(可能是未知长度),那么你也需要遍历它。
foreach( $array as $index => $val ){
if( is_array( $val ) ){
foreach( $val as $i => $arr ) echo $arr;
} else {
echo $val;
}
}
答案 1 :(得分:0)
您可以使用print_r()
,var_dump()
或使用foreach()
打印 - 但您做错了!
print_r($array); //will print the whole array
var_dump($array); //will print the whole array plus variable type and length
foreach($array as $arr){
//$arr is the array VALUE!
if(!is_array($arr)) echo $arr;
else echo $arr[0];
}
答案 2 :(得分:0)
试试这个
foreach ($array as $key => $value) {
if (is_array($value) && count($value) > 0) {
foreach ($value as $key1 => $val1) {
echo $val1;
}
} else {
echo $value;
}
}
答案 3 :(得分:0)
function print_array($array){
foreach ($array as $value){
if (is_array($value)){
print_array($value);
}
else{
echo $value;
}
}
}
$array = array('a', 'b', array('c', 'd'));
print_array($array);
答案 4 :(得分:0)
如果您不知道叠层阵列的数量,最好的方法是递归:
function print_table($table){
foreach ($table as $key => $value) {
if (is_array($value)) {
print_table($value);
} else {
echo "<p> $key -> $value </p>";
}
}
}
为例
$fruits = array (
"fruits" => array("a" => "orange", "b" => array("a" => "orange", "b" => "banana", "c" => "apple"), "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
print_table($fruits);
答案 5 :(得分:-1)
foreach($array as $arr){
print_r($arr);
}