AGoberg
AGoberg

Reputation: 35

Displaying an PHP Array in a readable format

I'm a newbie when it comes to PHP, so I'm sorry if this is too simple and obvious.

I have a webform that users can add input fields to dynamically. When the user clicks submit all the input fields are saved into an array. When I use the print_r command I get an array that looks like this:

Array 
    ( 
    [1] => Array ( [tc] => 00:10 [feedback] => good ) 
    [2] => Array ( [tc] => 00:20 [feedback] => bad ) 
    [3] => Array ( [tc] => 00:21 [feedback] => Bigger text ) 
    )

The code I use to pull the data into the array is:

if (!empty($_POST)) { //The values have been posted
    $elements = array();
    foreach ($_POST as $key => $val) { //For every posted values
        $frags = explode("_", $key); //we separate the attribute name from the number
        $id = $frags[1]; //That is the id
        $attr = $frags[0]; //And that is the attribute name
        if (!empty($val)) {
            //We then store the value of this attribute for this element.
            $elements[$id][$attr] = htmlentities($val);
        }
    }
}

The way I would like to display the data is like this:

01: 00:10 - good<br />
02: 00:20 - bad<br />
03: 00:21 - Bigger text<br />

The form I am trying to make can be found at http://ridefreemedia.com.au/test

Upvotes: 1

Views: 200

Answers (4)

zsaat14
zsaat14

Reputation: 1118

Just call the array like this $array_name[1]. Or, if the array value has a key, $array_name['key_name'].

Upvotes: 0

Jerska
Jerska

Reputation: 12002

You have to iterate on the array, as such:

$arr = Array( 
    1 => Array ( "tc" => "00:10", "feedback" => "good" ),
    2 => Array ( "tc" => "00:20", "feedback"=> "bad" ),
    3 => Array ( "tc" => "00:21", "feedback" => "Bigger text" ) 
  );

foreach ($arr as $k => $info) {
  echo $k . ': ' . $info['tc'] . ' - ' . $info['feedback'] . '<br />'; 
}

Here the output will be:

1: 00:10 - good
2: 00:20 - bad
3: 00:21 - Bigger text

2 notables things, as I believe you're discovering PHP:

  • . concatenates strings
  • foreach ($array as $k => $v) iterates over the array.
    For each line, it puts the key of the line in $k, and the value in $v. Here, $k = 1 and $info = Array ( "tc" => "00:10", "feedback" => "good" ) on the first iteration.

Upvotes: 1

Tarek Hassoun
Tarek Hassoun

Reputation: 13

print_r won't do, as you can see it outputs the meta data of the array. try adding the field to a string and use echo to output the strings into the html code.

Upvotes: 0

GluePear
GluePear

Reputation: 7715

It's not exactly what you're after, but <pre> would prettify it a bit.

echo '<pre>';
print_r($val);
echo '</pre>';

Upvotes: 0

Related Questions