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.
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With