Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display an array in a readable/hierarchical format

Tags:

sql

php

Here is the code for pulling the data for my array

<?php
    $link = mysqli_connect('localhost', 'root', '', 'mutli_page_form');

    $query = "SELECT * FROM wills_children WHERE will=73";

    $result = mysqli_query($link, $query) or die(mysqli_error($link));

    if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    if($row = mysqli_fetch_assoc($result)) {
        $data = unserialize($row['children']);
    }

    /* free result set */
    mysqli_free_result($result);
    }
?>

When I use print_r($data) it reads as:

Array ( [0] => Array ( [0] => Natural Chlid 1 [1] => Natural Chlid 2 [2] => Natural Chlid 3 ) ) 

I would like it to read as:

Natural Child 1
Natural Child 2
Natural Child 3

like image 917
Xavier Avatar asked Mar 22 '11 14:03

Xavier


People also ask

Which function is used to return an array in human readable form?

If you are just looking for a readable form on an array you could also try ArrayToJSON with the pPretty parameter set to true. This gives a nicely laid out text representation.

How do I print an array format?

Print an Array Using Arrays. toString() and Arrays. deepToString() The built-in toString() method is an extremely simple way to print out formatted versions of objects in Java.


3 Answers

Instead of

print_r($data);

try

print "<pre>";
print_r($data);
print "</pre>";
like image 119
Phenex Avatar answered Sep 22 '22 14:09

Phenex


print("<pre>".print_r($data,true)."</pre>");
like image 35
Shankar ARUL Avatar answered Sep 20 '22 14:09

Shankar ARUL


I have a basic function:

function prettyPrint($a) {
    echo "<pre>";
    print_r($a);
    echo "</pre>";
}

prettyPrint($data);

EDIT: Optimised function

function prettyPrint($a) {
    echo '<pre>'.print_r($a,1).'</pre>';
}

EDIT: Moar Optimised function with custom tag support

function prettyPrint($a, $t='pre') {echo "<$t>".print_r($a,1)."</$t>";}
like image 20
ditto Avatar answered Sep 21 '22 14:09

ditto