When developing web applications, it is often necessary to display the data in the array on the web page using PHP language. In this case, the elements in the array need to be displayed on the web page in a certain way, for example, the content in the array must be displayed on the web page in a certain way. Displayed in tabular form.
In PHP, you can use HTML and CSS to display arrays in table form. Each row in the table corresponds to an element in the array, and each column corresponds to a key in the array. What we need to do is to map each element in the array to the corresponding column of the table according to the key.
Let’s look at an example below. Suppose we have an array that stores user information. The array includes the ID, name, age, and gender of each user. We need to display this array in table form, the code is as follows:
<?php $user_info = array( array('id' => '1', 'name' => 'Amy', 'age' => '23', 'gender' => 'Female'), array('id' => '2', 'name' => 'Bob', 'age' => '35', 'gender' => 'Male'), array('id' => '3', 'name' => 'Cathy', 'age' => '27', 'gender' => 'Female'), array('id' => '4', 'name' => 'David', 'age' => '41', 'gender' => 'Male'), array('id' => '5', 'name' => 'Emily', 'age' => '19', 'gender' => 'Female') ); echo '<table>'; echo '<tr><th>ID</th><th>Name</th><th>Age</th><th>Gender</th></tr>'; foreach ($user_info as $user) { echo '<tr>'; echo '<td>' . $user['id'] . '</td>'; echo '<td>' . $user['name'] . '</td>'; echo '<td>' . $user['age'] . '</td>'; echo '<td>' . $user['gender'] . '</td>'; echo '</tr>'; } echo '</table>'; ?>
In the above code, we first define an array $user_info that stores user information. Next, we defined a table in HTML and added a header to the table that included the names of each column. Then, we use a loop to traverse each element in the array and map the key value of each element to each column of the table, thereby displaying the array in the form of a table.
It should be noted that when the elements in the array are displayed on the web page, certain data formatting and data cleaning are required to ensure data security and format correctness. In the above example, we used HTML and CSS to implement the style setting of the table. This method can be modified and expanded according to needs to achieve a more flexible table display effect.
In general, displaying arrays in tabular form is one of the commonly used techniques in PHP. It can display the elements in the array well and provide users with a better reading experience.
The above is the detailed content of How to display arrays in corresponding columns in php. For more information, please follow other related articles on the PHP Chinese website!