[英]PHP recursion print all elements of a multidimensional array with keys
I found the following code, which prints all the elements of an array fine. 我找到了以下代码,它可以打印出数组中的所有元素。 How can I modify it to print a key one time and then all the values corresponding to the key, then another key, then all values corresponding to key? 如何修改它以打印一次键,然后是键对应的所有值,然后是另一个键,那么所有与键对应的值? I also would like to modify it so it only prints the first 9 values (no more than this) for each key. 我也想修改它,因此它只打印每个键的前9个值(不超过这个值)。
function printAll($a) {
if (!is_array($a)) {
echo $a, ' ';
return;
}
foreach($a as $v) {
printAll($v);
}
}
I am assuming you want something non-programming humans can make some sort of sense out of. 我假设你想要一些非编程人类可以从某种意义上做出某种意义。
function pretty_dump($arr, $d=1){
if ($d==1) echo "<pre>"; // HTML Only
if (is_array($arr)){
foreach($arr as $k=>$v){
for ($i=0;$i<$d;$i++){
echo "\t";
}
if (is_array($v)){
echo $k.PHP_EOL;
Pretty_Dump($v, $d+1);
} else {
echo $k."\t".$v.PHP_EOL;
}
}
}
if ($d==1) echo "</pre>"; // HTML Only
}
Usage: 用法:
$myarray=array(
'mammals'=>array(
'cats'=>array(
'cheetah',
'lion',
'cougar'
),
'dogs'=>array(
'big'=>'Scooby',
'small'=>'chihuahua',
'medium'=>array(
'pumi',
'bulldog',
'boxer'
)
),
),
'fish'=>'fish',
'birds'=>array(
'flying'=>array(
'mallard',
'condor',
'gull'
),
'nonflying'=>'emu'
)
);
pretty_dump($myarray);
Output: 输出:
mammals
cats
0 cheetah
1 lion
2 cougar
dogs
big Scooby
small chihuahua
medium
0 pumi
1 bulldog
2 boxer
fish fish
birds
flying
0 mallard
1 condor
2 gull
nonflying emu
function printAll($a) {
if (!is_array($a)) {
echo $a, ' ';
return;
}
foreach($a as $k => $value) {
if($k<10){
printAll($k);
printAll($value);
}
}
}
What's wrong with print_r
, var_dump
or var_export
? print_r
, var_dump
或var_export
什么问题?
That aside, read the documentation on foreach
and you'll clearly see how to get the key you're iterating over. 除此之外,阅读有关foreach
的文档,您将清楚地看到如何获得您正在迭代的密钥。
function printAll($a) {
foreach ($a as $k => $v) {
echo $k, ' ';
}
printAllVals($a);
}
function printAllVals($a) {
if (!is_array($a)) {
echo $a, ' ';
return;
}
foreach($a as $k => $v) {
if ($k < 10) {
printAllVals($v);
}
}
}
Try with: 试试:
foreach($a as $k => $v)
where $k
is your key and $v
is still value. 其中$k
是你的钥匙而$v
仍然是价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.