Need help on how to approach with array manipulation to create a table?

I have two arrays that will always have the same length:

$unit = array('a','b','c','d','a','b','d');
$type = array('x','y','z','x','y','z','x');

There may also be more unit types or types. Example: Units can be me 5 instead of 4 (a, b, c, d) or type can be 5 instead of 3 (x, y, z). But the length of the two arrays is the same.

Now with this data, I want to create a table as follows:

   x     y     z     
a  1     1  
b        1     1
c              1
d  2

What i have done so far:

$TYPE = array_values(array_unique($type));
$UNIT = array_values(array_unique($unit));

These two will contain the first column and the top row.

echo "<table border='1' cellpadding='5' cellspacing='0' style='border-collapse:collapse;'>"; 
   echo "<tr><td>" . '  '  . "</td>";
   $lengthtype = count($TYPE);
   for($i=0; $i<$lengthtype; $i++)
   {
       echo "<td>" . $TYPE[$i] . "</td>";
   }
   echo "</tr>";        
   $unitlength = count($UNIT);
   for($i=0; $i<$unitlength;$i++)
   {
     echo "<tr>";
     echo "<td>" . $UNIT[$i] . "</td>";
     echo "</tr>";
   }  
echo "</table>";

I decided that I needed to combine these two to create a 2D array, so I did this:

$newarray = array();
foreach($type as $key=>$val)
{
    $newarray[$key][]=$val;
    $newarray[$key][]=$unit[$key];
}

Now I can not determine what is the effective way to continue?

If you guys can give any hint that will be wonderful.

UPDATED:

- . , 1 2 , .

+4
1

:

for , $TYPE subArray subArray , $UNIT .

, :

Array
(
   //↓ Each '$TYPE'
    [x] => Array
        (
            [a] => 1
            [d] => 2
           //↑     ↑ Amount
           //Each '$UNIT', which occurs at the same position as this type 
        )

    [y] => Array
        (
            [b] => 1
            [a] => 1
        )

    [z] => Array
        (
            [c] => 1
            [b] => 1
        )

)

. $UNITS, array_unique(). $TYPE. , , .

:

<?php

    $UNIT = array('a','b','c','d','a','b','d');
    $TYPE = array('x','y','z','x','y','z','x');

    $count = [];

    for($i = 0, $length = count($UNIT); $i < $length; $i++) {
        if(!isset($count[$TYPE[$i]][$UNIT[$i]]))
            $count[$TYPE[$i]][$UNIT[$i]] = 0;
        $count[$TYPE[$i]][$UNIT[$i]]++;
    }


    echo "<table border='1' cellpadding='5' cellspacing='0' style='border-collapse:collapse;'>";
    echo "<tr><td></td><td>" . implode("</td><td>", array_unique($TYPE)) . "</td></tr>";
    foreach(array_unique($UNIT) as $key){
        echo "<tr><td>$key</td>";
        foreach(array_unique($TYPE) as $v)
            echo "<td>" . (isset($count[$v][$key]) ? $count[$v][$key] : "") . "</td>";
        echo "<tr>";
    }
    echo "</table>";

?>

:

    x   y   z
a   1   1   
b       1   1
c           1
d   2       
+3

Source: https://habr.com/ru/post/1605600/


All Articles