Transpose rows and columns in a 2D array [duplicate] - php

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 4 years ago.
I have created a table that displays a series of numbers in a table. I am trying to transpose the matrix (flip rows and columns) using a for each loop and a function named transpose_matrix but it doesnt seem to be working for me. Where am I going wrong with this? I am working with the following code:
//Creating rows and columns for text file
echo "<h1>Data Table</h1>";
echo "<table border = 0 >";
foreach($result as $key=>$value){
echo "<tr>";
foreach($value as $v){
echo "<td>".$v."</td>";
}
echo "</tr>";
}
echo "</table>";
}
function transpose_matrix($result) {
$transpose = array(); //
foreach ($result as $key => $sub) {
foreach ($sub as $subkey => $subvalue) {
$transpose[$subkey][$key] = $subvalue;
}
}
return $transpose;
}
My first table displays as expected and looks somthing like this:
1 2 3 4 5
6 7 8 9 10
I need it to appear as such (i.e rotating the position of the rows and columns):
1 6
2 7
3 8
4 9
5 10
I have searched StackOverflow for similar questions or solutions but cannot seem to find one that works. I am fairly new to PHP also so apologies if it is a simple fix

This should give you what you need.
function transpose($array_one) {
$array_two = [];
foreach ($array_one as $key => $item) {
foreach ($item as $subkey => $subitem) {
$array_two[$subkey][$key] = $subitem;
}
}
return $array_two;
}
Then just pipe your existing array into the function and render the resulting array.

Check this: https://3v4l.org/OnuSu
$table = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
];
$i = 0;
$transpose = [];
while ($columns = array_column($table, $i++))
{
$transpose[] = $columns;
}
$table = '<table border="1">';
$rows = count($transpose);
for ($i = 0; $i < $rows; $i++){
$cols = count($transpose[$i]);
$table .= '<tr>';
for ($j = 0; $j < $cols; $j++)
{
$table .= '<td>' . $transpose[$i][$j] . '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
echo $table;

You can just extract the columns of the sub-arrays one-by-one:
foreach(reset($result) as $key => $values) {
$transpose[] = array_column($result, $key);
}
However this is probably better and should work even if the keys are different in each array:
$transpose = array_map(null, ...$result);

Your function seems to be working fine you just need to call it.
Add this below the function:
//Creating rows and columns for text file
$result[0] = ['1','2','3','4','5'];
$result[1] = ['6','7','8','9','10'];
$result[2] = ['11','12','13','14','15'];
$result[3] = ['16','17','18','19','20'];
$result[4] = ['21','22','23','24','25'];
echo "<h1>Data Table</h1>";
echo "<table border = 0 >";
foreach($result as $key=>$value){
echo "<tr>";
foreach($value as $v){
echo "<td>".$v."</td>";
}
echo "</tr>";
}
echo "</table>";
function transpose_matrix($result) {
$transpose = array(); //
foreach ($result as $key => $sub) {
foreach ($sub as $subkey => $subvalue) {
$transpose[$subkey][$key] = $subvalue;
}
}
return $transpose;
}
$mat = transpose_matrix($result);
echo "<h1>Data Table</h1>";
echo "<table border = 0 >";
foreach($mat as $key=>$value){
echo "<tr>";
foreach($value as $v){
echo "<td>".$v."</td>";
}
echo "</tr>";
}
echo "</table>";

Related

a PHP table map

I want to create a game where I have to create a map with PHP. I want to create 100 tables boxes in the right way but I can't get it work...
$field = 100;
echo "<table border='3px' dir='ltr'>";
for ($row=0; $row < 10 ; $row++) {
echo "<tr>";
for ($column=0; $column < 10; $column++) {
echo "<td>";
echo $field;
$field--;
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
This gives me this table:
But I will need a table like:
If a for loop is not a requirement.
I would use an array, then you have a set to work from rather then calculating things, then you just need reverse the odd row, like so:
$rows = array_reverse(array_chunk(range(1, 100), 10));
echo "<table>\n";
foreach ($rows as $level => $row) {
if (($level-1) % 2) {
$row = array_reverse($row);
}
echo "\t<tr>\n";
foreach ($row as $value) {
echo "\t\t<td>$value</td>\n";
}
echo "\t</tr>\n";
}
echo "<table>\n";
https://3v4l.org/204eh

apply css to specific element in array

I am fetching data of employees from mysql database into array and displaying in table.
everything is working but i want to apply a condition in array that
If salary is greater then 30,000 then change its color to red .
Tried
$q = "select name, salary from array";
$res = mysqli_query($link, $q);
$arr = array();
while ($data = mysqli_fetch_assoc($res)) {
$arr[] = $data;
}
echo '<table class="table table-hover">
<th>Name</th><th>Salary</th>';
$keys = array_keys($arr);
foreach ($keys as $key => $value) {
echo "$value , ";
}
for ($i=0; $i < count($arr); $i++) {
echo '<tr>';
foreach ($arr[$keys[$i]] as $key => $value) {
if ($arr[$keys[$i]['salary']] > 34000) {
echo "<td style='color: red; background-color:pink;'> $key=>$value </td>";
}else{
echo "<td> $key=>$value </td>";
}
}
echo "</tr>";
}
echo '</table>';
this is how my table looks
i want to change color of salary if it is greater than 30,000...
Change
if ($arr[$keys[$i]['salary']] > 34000) {
to
if ($value > 30000) {
I think you just got a little lost when processing an array which contains another arrays. A simple foreach loop is the simplest way of dealing with this.
echo '<table class="table table-hover"><th>Name</th><th>Salary</th>';
foreach ($arr as $row) {
echo '<tr>';
// using a ternary operator here rather than an IF
$style = $row['salary'] > 30000
? ' style="color:red;background-color:pink;"'
: '';
echo "<td>{$row['name']}</td>";
echo "<td $style>{$row['salary']}</td>";
echo '</tr>';
}

Split flat array into 4 transposed subarrays and print as html table [duplicate]

This question already has answers here:
Chunk and transpose a flat array into rows with a specific number of columns
(3 answers)
Closed 10 months ago.
I want to add foreach entry sequence wise for example
suppose my array like this
$arr = array('111','222','333','444','555','666','777','888','999'..so on);
Now using foreach, I want to enter print the array data like this:
<div>
<p>111</p>
<p>555</p>
<p>999</p>
</div>
<div>
<p>222</p>
<p>666</p>
</div>
<div>
<p>333</p>
<p>777</p>
</div>
<div>
<p>444</p>
<p>888</p>
</div>
Here is execution how to do it.
First create split array, which groups necessary elements into 4 groups. Then in second foreach, each is formatted. This is an example, may not be very effective in large data arrays.
$arr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
$split = [];
foreach ($arr as $k => $v) {
$split[$k % 4][] = $v;
}
$out = '';
foreach ($split as $row) {
$out .= '<div>';
foreach ($row as $e) {
$out .= '<p>' . $e . '</p>';
}
$out .= '</div>';
}
Another way you could do it, similar to tilz0R
<?php $rowArray = array();
$counter = 1;
foreach ($arr as $item){
$rowArray[$counter][] = $item;
if ($counter == 3){$counter = 1;}else{$counter++;}
}
foreach ($rowArray as $row)
{
?><div>
<?php foreach ($row as $item)
{
?><p><?= $item?></p>
<?php }?></div><?php
};?>
You can use array_walk:
const NB_ROWS = 4;
for ($row = 0; $row < NB_ROWS; $row++) {
echo "<div>\n";
array_walk($arr, function($item, $key, $row) { if($key % NB_ROWS == $row) echo "<p>$item</p>\n"; }, $row);
echo "</div>\n";
}
Or to be clearer:
Define a function that will print only elements of the given row:
function printRow($item, $key, $row)
{
if($key % 4 == $row) {
echo "<p>$item</p>\n";
}
}
Then call it once for each row:
for ($row = 0; $row < 4; $row++) {
echo "<div>\n";
array_walk($arr, 'printRow', $row);
echo "</div>\n";
}

How to get keys in a PHP array with null values?

When I print an array with a string as $key and an array as $value using foreach ($array key => value), the keys with null values are not displayed. Can someone please help me with this?
$stockist = array();
while($row = mysql_fetch_array($result)) {
$pharmacy = trim($row['pharmacy']);
if (isset($stockist[$pharmacy])) {
$medicine = $stockist[$pharmacy];
$medicine[] = trim($row['pharmacy']);
$stockist[$pharmacy] = $medicine;
}
else {
$medicine = array();
$medicine[] = trim($row['medicine']);
$stockist[$pharmacy] = $medicine;
}
}
ksort($stockist);
foreach ($stockist as $key => $value) {
echo "<table align='center' border='1'>";
echo "<tr><td align = 'justify'> <font color = 'blue'> $key</td></tr>";
foreach ($value as $key1 => $value1) {
echo "<tr><td align ='justify'>$value1</td></tr><br>";
}
echo "</table>";
}
This isn't exactly what you're looking for, but it is what the title is asking for ("How to get keys in a PHP array with null values?"--my own question that brought me to this page):
function find_nulls($a) {
return array_keys(array_filter($a, function($b) {
return is_null($b);
}) );
}
You can use for loop instead of foreach.
$stockCount = count($stockist);
for ($stockCount; $i <=0; $i++) {
echo "<table align='center' border='1'>";
echo "<tr><td align = 'justify'> <font color = 'blue'> $stockCount[$i]</td></tr>";
echo "</table>";
}
Hope it will work.

Building a Table of Data with an Array of Arrays

I have an Array of Arrays and Want to create a Tabular data layout. This is not the exact code, as how their generated is quite the cluster (Coming from COBOL interaction) but this should give me enough to make it work if someone can think of a clean way to code this.
array(
Array(847.0, 97010, 11)
Array(847.0, 97012, 10)
Array(847.1, 97010, 08)
Array(847.1, 97012, 14)
)
So I want to put these into a Table that looks something like
97010 97012
847.0 11 10
847.1 08 14
The first 2 elements of the arrays will always be the two axis and the 3rd the contents of the table.
Any Suggestions? thanks!
$table = array();
$columns = array();
// copy the array (x, y, value) into a table
// keeping track of the unique column names as we go
foreach ($dataSet as $point) {
// provided sample data used floats, ensure it is a string
$x = strval($point[0]);
$y = strval($point[1]);
$data = $point[2];
if (!isset($table[$x])) {
$table[$x] = array();
}
$table[$x][$y] = $data;
// quick and dirty style 'unique on insert'
$columns[$y] = true;
}
// switch the column names from title => true to just titles
$columns = array_flip($columns);
// Display the table
echo '<table>';
// Header row
echo '<tr>';
echo '<th> </th>';
foreach ($columns as $columnTitle) {
echo '<th>' . $columnTitle . '</th>';
}
echo '</tr>';
// Bulk of the table
foreach ($table as $rowTitle => $row) {
echo '<tr>';
echo '<th>' . $rowTitle . '</th>';
foreach ($columns as $columnTitle => $junk) {
if (isset($row[$columnTitle]) {
echo '<td>' . $row[$columnTitle] . '</td>';
} else {
// Handle sparse tables gracefully.
echo '<td> </td>';
}
}
echo '</tr>';
}
echo '</table>';
From what I understood:
$arr[847.0][97010] = '11';
$arr[847.0][97012] = '10';
$arr[847.1][97010] = '08';
$arr[847.1][97012] = '14';
And you may create a table:
$result = "<table>";
foreach($arr as $row_key => $row) {
$result .= "<tr>";
foreach($row as $column_key => $data) {
$result .= "<td>".$data."</td>";
}
$result .= "</tr>";
}
$result .= "</table>";
echo $result;

Categories