Displaying HTML table from PHP array with two headers - php

I have an array containing sport results that looks like this:
Array
(
[0] => Array
(
[name] => Alexander
[distance] => 60
[value] => 9
)
[1] => Array
(
[name] => Alexander
[distance] => 100
[value] => 10
)
[2] => Array
(
[name] => Alexander
[distance] => 200
[value] => 11
)
[3] => Array
(
[name] => Alexander
[distance] => 400
[value] => 12
)
[4] => Array
(
[name] => Dmitriy
[distance] => 60
[value] => 5
)
[5] => Array
(
[name] => Dmitriy
[distance] => 100
[value] => 6
)
[6] => Array
(
[name] => Dmitriy
[distance] => 200
[value] => 7
)
[7] => Array
(
[name] => Dmitriy
[distance] => 400
[value] => 8
)
[8] => Array
(
[name] => Sergei
[distance] => 60
[value] => 1
)
[9] => Array
(
[name] => Sergei
[distance] => 100
[value] => 2
)
[10] => Array
(
[name] => Sergei
[distance] => 200
[value] => 3
)
[11] => Array
(
[name] => Sergei
[distance] => 400
[value] => 4
)
)
I need to display the array data in a specific way in a html table, that should look like this. Top header should contain all unique values from "distance" key and left header should contain all unique values from "name" key:
| 60 | 100 | 200 | 400
===========================================
Alexnader | 9 | 10 | 11 | 12
===========================================
Dmitriy | 5 | 6 | 7 | 8
===========================================
Sergei | 1 | 2 | 3 | 4
How can I do it the fastest way, with the least number of loops or using php array methods? Thank you.

Get unique distances and names for the table.
$names = array_unique(array_map(fn($a) => $a['name'], $data));
$dists = array_unique(array_map(fn($a) => $a['distance'], $data));
Make a function to find by name and distance for table values.
function findValue($dist, $name, $data): string {
foreach($data as $d) {
if($d['name'] != $name || $d['distance'] != $dist ) continue;
return (string) $d['value'];
}
return '';
}
Now out output the table beginning with the head and distances
echo "<table>\n";
echo "<tr><th></th>", implode('', array_map(fn($col) => "<th>$col</th>", $dists)), "</tr>\n";
Put out the data by row for each name using our find function
foreach($names as $name) {
$row = [];
foreach($dists as $dist) {
$row[] = '<td>' . findValue($dist, $name, $data) . '</td>';
}
$rowText = join('', $row);
echo "<tr><td>$name</td>$rowText</tr>\n";
}
Finally close the table.
echo "</table>\n";
The result is
<table>
<tr><th></th><th>60</th><th>100</th><th>200</th><th>400</th></tr>
<tr><td>Alexander</td><td>9</td><td>10</td><td>11</td><td>12</td></tr>
<tr><td>Dmitriy</td><td>5</td><td>6</td><td>7</td><td>8</td></tr>
<tr><td>Sergei</td><td>1</td><td>2</td><td>3</td><td>4</td></tr>
</table>

We have to restructure the array first
$array = Array
(
"0" => Array
(
"name" => "Alexander",
"distance" => 60,
"value" => 9
),
"1" => Array
(
"name" => "Alexander",
"distance" => 100,
"value" => 10
),
"2" => Array
(
"name" => "Alexander",
"distance" => 200,
"value" => 11
),
"3" => Array
(
"name" => "Alexander",
"distance" => 400,
"value" => 12
),
"4" => Array
(
"name" => "Dmitriy",
"distance" => 60,
"value" => 5
),
"5" => Array
(
"name" => "Dmitriy",
"distance" => 100,
"value" => 6
),
"6" => Array
(
"name" => "Dmitriy",
"distance" => 200,
"value" => 7
),
"7" => Array
(
"name" => "Dmitriy",
"distance" => 400,
"value" => 8
),
"8" => Array
(
"name" => "Sergei",
"distance" => 60,
"value" => 1
),
"9" => Array
(
"name" => "Sergei",
"distance" => 100,
"value" => 2
),
"10" => Array
(
"name" => "Sergei",
"distance" => 200,
"value" => 3
),
"11" => Array
(
"name" => "Sergei",
"distance" => 400,
"value" => 4
)
);
$table_heading = array_unique(array_column($array, "distance"));
$restructured_array = [];
foreach($array as $row){
if(!isset($restructured_array[$row["name"]])){
$restructured_array[$row["name"]] = [];
}
$restructured_array[$row["name"]][$row["distance"]] = $row["value"];
}
Now the array can be looped to print the table.
echo "<table><thead><tr>";
echo "<th></th>";
foreach($table_heading as $heading){
echo "<th>".$heading."</th>";
}
echo "</tr></thead>";
echo "<tbody>";
foreach ($restructured_array as $key=>$rows){
echo "<tr><th>".$key."</th>";
foreach ($rows as $k=>$row){
echo "<td>".$row."</td>";
}
}
echo "</tbody></table>";
The output will be
60 100 200 400
Alexander 9 10 11 12
Dmitriy 5 6 7 8
Sergei 1 2 3 4

Related

PHP : Add lowest value from duplicate records of array

I want to remove duplicate record which is highest value in array.
Array :
Array
(
[0] => Array
(
[id] => 1
[number] => 123
[price] => 6
)
[1] => Array
(
[id] => 2
[number] => 456
[price] => 6
)
[2] => Array
(
[id] => 3
[number] => 123
[price] => 5
)
)
Expected Result :
Array
(
[0] => Array
(
[id] => 2
[number] => 456
[price] => 6
)
[1] => Array
(
[id] => 3
[number] => 123
[price] => 5
)
)
number is duplicate field and after that need to compare price. Which will be lower that will be display. Rest of all should be removed.
What I tried :
$lowest = min($myArray);
$result = array_filter($myArray, function($value, $key) use ($lowest) {
return $value === $lowest;
}, ARRAY_FILTER_USE_BOTH);
How can i do that?
UPDATE :
#Daniel Dez solution is almost working. I used 3rd solution of him. But, It should be working like this.
For ex : number 123 is duplicate records now it's lowest price is 2. Then, it should be display rest of 123 number's array element remove.
Array :
$data = [
[
"id" => 1,
"number" => 123,
"price" => 2,
],
[
"id" => 2,
"number" => 456,
"price" => 6,
],
[
"id" => 3,
"number" => 123,
"price" => 5,
],
[
"id" => 4,
"number" => 123,
"price" => 11,
],
[
"id" => 5,
"number" => 456,
"price" => 5,
],
[
"id" => 6,
"number" => 123,
"price" => 5,
]
];
Expected Output :
Array
(
[0] => Array
(
[id] => 1
[number] => 123
[price] => 2
)
[1] => Array
(
[id] => 2
[number] => 456
[price] => 5
)
)
please help me.
Thanks.
Data:
$numbers = array_unique(array_column($data, 'number'));
usort($data, function ($a, $b) {
return $a['price'] - $b['price'];
});
$result = [];
foreach ($numbers as $number) {
foreach ($data as $item) {
if ($item['number'] == $number) {
break;
}
}
$result[] = $item;
}
print_r($result);

sum array indexes with same value for a specific key

I have the following array:
[0] => Array
(
[id] => 1
[uid] => 50
[sum1] => 1
[sum2] => 2
)
[1] => Array
(
[id] => 2
[uid] => 50
[sum1] => 2
[sum2] => 4
)
[2] => Array
(
[id] => 3
[uid] => 51
[sum1] => 3
[sum2] => 5
)
As you can see, on some of those indexes, [uid] is the same. The length and data of the array is dynamic.
what i need to do is merge the indexes that have the same value for[uid] and sum the values for the other keys:
[0] => Array
(
[id] => 2
[uid] => 50
[sum1] => 3
[sum2] => 6
)
[1] => Array
(
[id] => 3
[uid] => 51
[sum1] => 3
[sum2] => 5
)
But for the life of me, i can't figure out how to do that.
Any help appreciated!
You can do it like this way,
<?php
$mainArray = [
0 => Array
(
'id' => 1,
'uid' => 50,
'sum1' => 1,
'sum2' => 2
),
1 => Array
(
'id' => 2,
'uid' => 50,
'sum1' => 2,
'sum2' => 4
),
2 => Array
(
'id' => 3,
'uid' => 51,
'sum1' => 3,
'sum2' => 5
)
];
$newArray=[];
foreach ($mainArray as $value) {
if(!array_key_exists($value['uid'], $newArray)){
// Store first time
$newArray[$value['uid']] = $value;
}else{
// Already exist, then sum and replace it
$newArray[$value['uid']]['id'] = $value['id'];
$newArray[$value['uid']]['sum1'] += $value['sum1'];// Sum with previous value
$newArray[$value['uid']]['sum2'] += $value['sum2'];// Sum with previous value
}
}
$newArray = array_values($newArray);// Reset indexes, Start the array index with zero
print_r($newArray);// To see the output
Output:
Array
(
[0] => Array
(
[id] => 2
[uid] => 50
[sum1] => 3
[sum2] => 6
)
[1] => Array
(
[id] => 3
[uid] => 51
[sum1] => 3
[sum2] => 5
)
)
I think you are correct. Actually, i solved the problem using something similar:
$sumArray = Array();
foreach ($array1 as $item){
if(isset($sumArray[$item['uid']])){
$sumArray[$item['idPartener']]['sum1'] += $item['sum1'];
$sumArray[$item['idPartener']]['sum2'] += $item['sum2'];
}else{
$sumArray[$item['uid']] = Array(
'id' => $item['id'],
'sum1' => $item['sum1'],
'sum2' => $item['sum2'] ,
);
}
}
Thanks all for your help!

Merging two multi-dimensional arrays using key and adding values

I want to merge two array's using key(product_id) and adding that values(usage).
Array 1
Array
(
[0] => Array
(
[name] => Reschedule A Service
[usage] => 1
[product_id] => 8
)
[1] => Array
(
[name] => Adding An Image
[usage] => 1
[product_id] => 5
)
[2] => Array
(
[name] => Each Calendar Event
[usage] => 1
[product_id] => 14
)
)
Array 2
Array
(
[0] => Array
(
[name] => Adding An Image
[usage] => 1
[product_id] => 5
)
[1] => Array
(
[name] => Schedule A Service
[usage] => 3
[product_id] => 11
)
[2] => Array
(
[name] => Each Calendar Event
[usage] => 2
[product_id] => 14
)
[3] => Array
(
[name] => Sales Performance Dashboard
[usage] => 2
[product_id] => 30
)
[4] => Array
(
[name] => Quote
[usage] => 1
[product_id] => 32
)
)
I need an out put like this merging and adding usage values.
Array
(
[0] => Array
(
[name] => Adding An Image
[usage] => 2
[product_id] => 5
)
[1] => Array
(
[name] => Schedule A Service
[usage] => 3
[product_id] => 11
)
[2] => Array
(
[name] => Each Calendar Event
[usage] => 3
[product_id] => 14
)
[3] => Array
(
[name] => Sales Performance Dashboard
[usage] => 2
[product_id] => 30
)
[4] => Array
(
[name] => Quote
[usage] => 1
[product_id] => 32
)
[5] => Array
(
[name] => Reschedule A Service
[usage] => 1
[product_id] => 8
)
)
This is my code for creating arrays
foreach($query->rows as $product){
$top_products[]=array(
'name'=>$product['name'],
'usage'=>$product['pusage'],
'product_id'=>$product['product_id']
);
}
foreach($query_2->rows as $product){
$top_point_products[]=array(
'name'=>$product['name'],
'usage'=>$product['p_usage'],
'product_id'=>$product['product_id']
);
}
$first =array(
array(
"name" => "Reschedule A Service",
"usage" => 1,
"product_id" => 8
),
array(
"name" => "Adding An Image",
"usage" => 1,
"product_id" => 5
),
array(
"name" => "Each Calendar Event",
"usage" => 1,
"product_id" => 14
)
);
$second =array(
array(
"name" => "Adding An Image",
"usage" => 1,
"product_id" => 5
),
array(
"name" => "Schedule A Service",
"usage" => 3,
"product_id" => 11
),
array(
"name" => "Each Calendar Event",
"usage" => 2,
"product_id" => 14
),
array(
"name" => "Sales Performance Dashboard",
"usage" => 2,
"product_id" => 30
),
array(
"name" => "Quote",
"usage" => 1,
"product_id" => 32
)
);
$result = array_unique(array_merge($first,$second), SORT_REGULAR);
Use array_unique & array_merge
Use the array_merge function, like this:
$C = array_merge($A, $B);
print_r($C);
Read manual Array merge
try this code
<?php
$array1=array
(
0 => array(
'name' => "Reschedule A Service",
'usage' => 1,
'product_id' => 8
),
1 => Array
(
'name' => "Adding An Image",
'usage' => 1,
'product_id' => 5
),
2 => Array
(
'name' => "Each Calendar Event",
'usage' => 2,
'product_id' => 14
)
);
$array2=array
(
0 => Array
(
'name' => "Adding An Image",
'usage' => 1,
'product_id' => 5
),
1 => Array
(
'name' => "Schedule A Service",
'usage' => 3,
'product_id' => 11
),
2 => Array
(
'name' => "Each Calendar Event",
'usage' => 5,
'product_id' => 14
),
3 => Array
(
'name' => "Sales Performance Dashboard",
'usage' => 2,
'product_id' => 30
),
4 => Array
(
'name' => "Quote",
'usage' => 1,
'product_id' => 32
)
);
$product_id1=array_column($array1, 'product_id');
$product_id2=array_column($array2, 'product_id');
$new=array_intersect($product_id1,$product_id2);
foreach ($new as $key => $value) {
if(in_array($new[$key],$product_id2)){
$array2[array_search($new[$key],$product_id2)]['usage']+=$array1[$key]['usage'];
}
}
$new1=array_diff($product_id1,$product_id2);
foreach ($new1 as $key => $value) {
$array2[]=$array1[$key];
}
foreach ($array2 as $key => $value) {
echo "[".$key."]=><br>";
foreach ($value as $key1 => $value1) {
echo "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp";
echo "[".$key1."]=>".$value1."<br>";
}
echo "<br>";
}
?>
output
[0]=>
[name]=>Adding An Image
[usage]=>2
[product_id]=>5
[1]=>
[name]=>Schedule A Service
[usage]=>3
[product_id]=>11
[2]=>
[name]=>Each Calendar Event
[usage]=>7
[product_id]=>14
[3]=>
[name]=>Sales Performance Dashboard
[usage]=>2
[product_id]=>30
[4]=>
[name]=>Quote
[usage]=>1
[product_id]=>32
[5]=>
[name]=>Reschedule A Service
[usage]=>1
[product_id]=>8
Use array_merge and a simple foreach loop to check your condition and update the usagevalues.
See below
$result = array_merge($arrArray1, $arrArray2);
$result2 = array();
foreach($result as $key => $value){
if(array_key_exists($value['product_id'], $result2)){
$result2[$value['product_id']]['usage'] += $value['usage'];
} else{
$result2[$value['product_id']] = $value;
}
}
print_r($result2);
If you want to reset your resultant array indexes use array_merge again like this
$result2 = array_merge($result2);
Hope this will help

How check array element exist in two-dimessional array in php [duplicate]

This question already has answers here:
How to search by key=>value in a multidimensional array in PHP
(17 answers)
Closed 9 years ago.
I have an array that is like:
Array
(
[0] => Array
(
[product_id] => 1
[product_name] => T-Shirts
[quantity] => 2
[price] => 300
)
[1] => Array
(
[product_id] => 2
[product_name] => Red Shirt
[quantity] => 4
[price] => 200
)
[2] => Array
(
[product_id] => 3
[product_name] => Cap
[quantity] => 2
[price] => 50
)
)
I want to check whether the product_id exist or not. I tried to in_array but did not get any result.
Is there any built-in function to check it without putting the array in loop.
As mentioned by gloomy.penguin, you could use array_filter
<?php
$a = Array
(
0 => Array
(
"product_id" => 1,
"product_name" => "T-Shirts",
"quantity" => 2,
"price" => 300,
),
1 => Array
(
"product_id" => 2,
"product_name" => "Red Shirt",
"quantity" => 4,
"price" => 200,
),
2 => Array
(
"product_id" => 3,
"product_name" => "Cap",
"quantity" => 2,
"price" => 50,
),
);
$result = array_filter($a, function($var) {
if ($var['product_id'] == 3) return true;
});
if (empty($result)) echo "Not found";
else echo "Found";
echo var_dump($result);
?>
You can loop through every product:
foreach($array as $product) {
if(isset($product['product_id']))
// do something
}
I don't think there's a built-in function to handle this.

Swap array Item with condition

I have the situation to swap array with condition.My array is plotted bellow.
pid => like primary key in mysql so it may loose it order
type=> type indicates, product type.array having 3 type of products.
Name=> Simply indicates product name
First I tried solution in mysql, But I didn't got any good sign.Some of them suggest me array swapping is better one. But I don't know How to get this one.
My problem
I am having list of items.When i listing products, type 3(mater) should not come at 5,10,15
(i.e modules of 5 ) positions.If it does my design getting collapse.
Screen Shot explanation
Perfect placement
Collapsed design
So i want to make sure type 3(master) never comes at mod of 5 position.How can i do this
Help me
My previous try in mysql here
Array
(
[0] => Array
(
[pid] => 1
[type] => 1
[name] => A
)
[1] => Array
(
[pid] => 2
[type] => 1
[name] => B
)
[2] => Array
(
[pid] => 3
[type] => 2
[name] => D
)
[3] => Array
(
[pid] => 4
[type] => 3
[name] => E(master)
)
[4] => Array
(
[pid] => 5
[type] => 3
[name] => f(sub)
)
[5] => Array
(
[pid] => 6
[type] => 1
[name] => A1
)
[6] => Array
(
[pid] => 7
[type] => 2
[name] => B1
)
[7] => Array
(
[pid] => 8
[type] => 1
[name] => C1
)
[8] => Array
(
[pid] => 9
[type] => 2
[name] => D1
)
[9] => Array
(
[pid] => 10
[type] => 3
[name] => E1(master)
)
[10] => Array
(
[pid] => 11
[type] => 3
[name] => A2(sub)
)
[11] => Array
(
[pid] => 12
[type] => 2
[name] => B2
)
[12] => Array
(
[pid] => 13
[type] => 1
[name] => C2
)
[13] => Array
(
[pid] => 14
[type] => 2
[name] => D2
)
[14] => Array
(
[pid] => 15
[type] => 1
[name] => E2
)
)
Thanks in advance
I gave it a try, the following code should do the trick. What I recommend is that you split up a block in the several subparts that define a block. Furthermore, it's not very DRY code, but it will give you an idea:
<?php
$grid = array(); $blocks = array();
$blocks[] = array(array("pid" => 1, "type" => 1, "name" => "A"));
$blocks[] = array(array("pid" => 2, "type" => 1, "name" => "B"));
$blocks[] = array(array("pid" => 3, "type" => 2, "name" => "D"));
$blocks[] = array(array("pid" => 4, "type" => 3, "name" => "E(master)"), array("pid" => 5, "type" => 3, "name" => "F (sub)"));
$blocks[] = array(array("pid" => 6, "type" => 1, "name" => "A1"));
$blocks[] = array(array("pid" => 7, "type" => 2, "name" => "B1"));
$blocks[] = array(array("pid" => 8, "type" => 1, "name" => "C1"));
$blocks[] = array(array("pid" => 9, "type" => 2, "name" => "D1"));
$blocks[] = array(array("pid" => 10, "type" => 3, "name" => "E1 (master)"), array("pid" => 11, "type" => 3, "name" => "A2 (sub)"));
$blocks[] = array(array("pid" => 12, "type" => 2, "name" => "B2"));
$blocks[] = array(array("pid" => 13, "type" => 1, "name" => "C2"));
$blocks[] = array(array("pid" => 14, "type" => 2, "name" => "D2"));
$blocks[] = array(array("pid" => 14, "type" => 1, "name" => "E2"));
$current_row = 0;
for ($n=0;$n < count($blocks);$n++) {
//Check if current row exists in grid
if (!isset($grid[$current_row]))
{
//Create new empty row in grid
$grid[$current_row] = array();
}
//check if current block fits
if (count($grid[$current_row]) + count($blocks[$n]) > 5)
{
// Block doesn't fit: Search for block that fits
for ($i=$n;$i < count($blocks);$i++)
{
if (count($grid[$current_row]) + count($blocks[$i]) <= 5)
{
//place parts in block on current row
foreach ($blocks[$i] as $part)
{
$grid[$current_row][] = $part;
}
//unset block from queue
unset($blocks[$i]);
}
}
//place current block on new row
$current_row++;
}
//place parts in block in grid
foreach ($blocks[$n] as $part)
{
$grid[$current_row][] = $part;
}
}
print_r($grid);
?>

Categories