PHP - Convert a multidimensional array to string?
I'm working on a small ajax application and need to see if the values being generated in the background are what is expected. The value returned by the quest can 开发者_高级运维be quite a complex multidimensional array, is there a way to convert this into a string so that it can be shown with alert?
Is there any other way of seeing these values?
Any advice appreciated.
Thanks.
print_r
, var_dump
or var_export
are good candidates. while coding an ajax application, you might also want to look at json_encode
.
If you want to show it with javascript, I would recommend json_encode()
, everything else has been covered by knittl's answer.
i work on a bunch of ajax apps.. in firefox i have an "add-on" called JSON view
then all my projects have a function
function test_array($array) {
header("Content-Type: application/json");
echo json_encode($array);
exit();
}
so whenever i want to see what the output is i just go test_array($something)
and it shows me the results.
its made debugging a breaze now
PS. know this Q is ancient and im not really answering the origional posters Q but might be useful for someone else aswell
<script type="text/javascript">
alert(<?=print_r($array)?>);
</script>
I found this function useful:
function array2str($array, $pre = '', $pad = '', $sep = ', ')
{
$str = '';
if(is_array($array)) {
if(count($array)) {
foreach($array as $v) {
$str .= $pre.$v.$pad.$sep;
}
$str = substr($str, 0, -strlen($sep));
}
} else {
$str .= $pre.$array.$pad;
}
return $str;
}
from this address: http://blog.perplexedlabs.com/2008/02/04/php-array-to-string/
Here is a simple answer in PHP:
function implode_recur($separator, $arrayvar) {
$output = "";
foreach ($arrayvar as $av)
if (is_array ($av))
$out .= implode_recur($separator, $av); // Recursive array
else
$out .= $separator.$av;
return $out;<br>
}
$result = implode_recur(">>",$variable);
The implode
command returns an array as a string.
you can also consider FirePHP http://www.firephp.org
精彩评论