我想打印一个数组,但不知道数组值的维度。 当我使用
echo '<pre>'
然后使用print_r($array)
时,它将显示Key
和value
,并用<br>
显示。 但是我只想显示数组的值而不是键。该$array
可能包含多维数组值或单个值或两者兼有。您需要使用递归函数:
$array_list = array('a',array(array('b','c','d'),'e')); // Your unknown array
print_array($array_list);
function print_array($array_list){
foreach($array_list as $item){
if(is_array($item)){
print_array($item);
}else{
echo $item.'<br>';
}
}
}
尝试使用这个递归
函数
function print_array($array, $space="")
{
foreach($array as $key=>$val)
{
if(is_array($val))
{
$space_new = $space." ";
print_array($val, $space_new);
}
else
{
echo $space." ".$val." ".PHP_EOL;
}
}
}
请参见演示
简而言之,您可以使用递归函数来实现您想要的目标:
function print_no_keys(array $array){
foreach($array as $value){
if(is_array($value)){
print_no_keys($value);
} else {
echo $value, PHP_EOL;
}
}
}
array_walk_recursive()
。
function print_no_keys(array $array, $indentSize = 4, $level = 0){
$indent = $level ? str_repeat(" ", $indentSize * $level) : '';
foreach($array as $value){
if(is_array($value)){
print_no_keys($value, $indentSize, $level + 1);
} else {
echo $indent, print_r($value, true), PHP_EOL;
}
}
}
示例:
<?php
header('Content-Type: text/plain; charset=utf-8');
$a = [1, [ 2, 3 ], 4, new stdClass];
function print_no_keys(array $array, $indentSize = 4, $level = 0){
$indent = $level ? str_repeat(" ", $indentSize) : '';
foreach($array as $value){
if(is_array($value)){
print_no_keys($value, $indentSize, $level + 1);
} else {
echo $indent, print_r($value, true), PHP_EOL;
}
}
}
print_no_keys($a);
?>
输出:
1
2
3
4
stdClass Object
(
)