...because you never shrink $prefix
after output(), try array_pop($prefix);
Alexander Skwar wrote:
Hello!
I'd like to print an array kinda like the way it was created. Ie., I've
got the following array:
$r[0][0]['name'] = 'joe';
$r[0][0]['gender'] = 'male';
$r[0][0]['prop'] = 'prefs';
$r[0][0][0]['text'] = 'mail';
$r[0][0][0]['set'] = 'yes';
$r[0][0][1]['text'] = 'phone';
$r[0][0][1]['set'] = 'no';
Now I'd like to have a function which I'd pass the array and get the
following output:
r[0][0]['name'] = 'joe'
r[0][0]['gender'] = 'male'
r[0][0]['prop'] = 'prefs'
r[0][0][0]['text'] = 'mail'
r[0][0][0]['set'] = 'yes'
r[0][0][1]['text'] = 'phone'
r[0][0][1]['set'] = 'no'
Right now, I've got the following not quite working function:
?php
function output($array, $name, $prefix = array()){
foreach ($array as $key = $value){
if (! is_array($value)){
if (0 count($prefix)){
// Prefix vorhanden
printf (%s%s[%s] = '%s'\n, $name, implode('', $prefix), $key, $value);
} else {
// Kein Prefix angegeben
printf (%s[%s] = %s\n, $name, $key, $value);
}
} else {
$prefix[] = sprintf('[%s]', $key);
output($value, $name, $prefix);
}
}
}
?
This produces the following output:
r[0][0][name] = 'joe'
r[0][0][gender] = 'male'
r[0][0][prop] = 'prefs'
r[0][0][0][text] = 'mail'
r[0][0][0][set] = 'yes'
r[0][0][0][1][text] = 'phone'
r[0][0][0][1][set] = 'no'
As you can see in the line with phone, I've still got an error
somewhere. The phone line should be:
r[0][0][1]['text'] = 'phone'
But it is:
r[0][0][0][1]['text'] = 'phone'
The 3rd [0] is too much. This means, that I somehow need to get rid of
the 3rd [0]. It seems like I did not notice that I went up again in
the array.
Could somebody please help me in refining the function so that it works?
Thanks a lot!
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php