Question

I have arrays like this:

$array1=array("x=1","y=2","y=3","z=3");
$array2=array("x=1","y=4","y=3","t=1");

I wanna print it exactly like this:

x   y   z   t
1   2,3 3   
1   4,3     1
Was it helpful?

Solution

You could do it like this:

<?php

// Data Source
$array = array("x=1","y=2","y=3","z=3");

// Helper Function
function parseArray($array)
{
    // Init
    $parsed_array = array();

    // Process Array
    foreach ($array as $item) {
        list($key, $value) = explode('=', $item);
        $parsed_array[$key][] = $value;
    }

    // Finished
    return $parsed_array;
}

// Usage
var_dump(parseArray($array));

Output:

enter image description here


If you want it to display it in like the said format; this is what you do this:

// Usage
$parsed_data = parseArray($array);
echo "<table border='1'>";
echo "<tr><th>". implode('</th><th>', array_keys($parsed_data)) ."</th></tr>";
echo "<tr>";
foreach ($parsed_data as $key => $values) {
    echo '<td>'.implode(',', $values).'</td>';
}
echo "</tr>";
echo "</table>";

Outputs:

enter image description here

OTHER TIPS

<?php

$arr = ["x=1","y=2","y=3","z=3"];
$multi = [];
foreach($arr as $value){
    $data = explode('=', $value);
    $multi[$data[0]][] = $data[1];
}

echo '<table><tr><th>';
echo implode('</th><th>', array_keys($multi));
echo '</th></tr><tr>';
foreach($multi AS $value){
    echo '<td>'.implode(',', $value).'</td>';
}
echo '</tr></table>';

Output when rendered as html:

x   y   z
1   2,3 3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top