0

I have 2 arrays and I would like to create automaticlly new rows in my table based on those arrays.

My arrays looks like this:

$array1['name1'] = "value1";
$array1['name2'] = "value2";
$array1['nameN'] = "valueN";

$array2['name1'] = "number1";
$array2['name2'] = "number2";
$array2['nameN'] = "numberN";

My html table output should look like this:

<table>
    <tr>
        <td>name1</td>
        <td>value1</td>
        <td>number1</td>
    </tr>
    <tr>
        <td>name2</td>
        <td>value2</td>
        <td>number2</td>
    </tr>
    <tr>
        <td>nameN</td>
        <td>valueN</td>
        <td>numberN</td>
    </tr>
</table>

I've been working on this 2 codes, but I don't know how to combine them:

<?php
foreach ($array1 as $name => $value) {
    echo '<tr><td>'.$name.'</td><td>'.$value.'</td></tr>';
    };
unset($nick, $value);
?>

<?php
foreach ($array2 as $name => $value) {
    echo '<tr><td>'.$name.'</td><td>'.$value.'</td></tr>';
    };
unset($nick, $value);
?>

Maybe I could combine both array in a multidimentional array and use some kind of foreach function like this:

$array = array();
$array['name1']['array1'] = "value1";
$array['name1']['array2'] = "number1";
$array['name2']['array1'] = "value2";
$array['name2']['array2'] = "number2";
$array['nameN']['array1'] = "valueN";
$array['nameN']['array2'] = "numberN";

Any help would be apriciated!

1 Answer 1

2

I assume both arrays have all the same keys.

foreach ($array1 as $name => $value) {
  echo '<tr><td>'.$name.'</td><td>'.$value.'</td><td>'.$array2[$name].'</td></tr>
}

It would be more straightforward if you used a two-dimensional array instead of two different arrays.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.