Interaction with multidimensional array in php

Asked

Viewed 45 times

2

I have that data:

$answers = [
    'text-1626173297126' => [
        'Capítulo teste',
        'Juarez Neri Antônio Pereira',
        'CAVALEIROS DA LUZ'
    ],
    'text-1626173306001' =>
    [
        'Pedro Ds',
        'RenGraminhani',
        'CAR CESAR TANURI'
    ],
    'text-1626173476932' => [
        '[email protected]',
        '[email protected]',
        'caranuri.com'
    ]
];

I need the first column (text-1626173297126) to be in the first column of an html table; text-1626173306001, in the second column; text-1626173476932, third;

I tried to do, something like:

foreach ($answers as $k => $value) {
    echo '<tr>';
    foreach ($value as $val) {

        echo '<td>', $val, '</td>';
    }
    echo '</tr>';
}

Desired exit

inserir a descrição da imagem aqui

1 answer

5


Want your data displayed in columns work them as if they were a table with array_column().

The function array_column() accepts a multidimensional array as input where each element(array or object) represents a row in a table, and each sub element(element element) represents a column in that table:

$answers = [
    'text-1626173297126' => [
        'Capítulo teste',
        'Juarez Neri Antônio Pereira',
        'CAVALEIROS DA LUZ'
    ],
    'text-1626173306001' =>
    [
        'Pedro Ds',
        'RenGraminhani',
        'CAR CESAR TANURI'
    ],
    'text-1626173476932' => [
        '[email protected]',
        '[email protected]',
        'caranuri.com'
    ]
];

foreach (range(0, count($answers) - 1) as $idx) {   //Itera pelos índices das linhas da tabela.
  echo '<tr>';
  foreach (array_column($answers, $idx) as $val){  //Itera pelas colunas dessa linha.
    echo '<td>', $val, '</td>';
  }
  echo '</tr>';
}

Test the code on Repl.it

Resulting in(HTML formatted and adapted for easy display):

<table>
  <tr>
    <td>Capítulo teste</td>
    <td>Pedro Ds</td>
    <td>[email protected]</td>
  </tr>
  <tr>
    <td>Juarez Neri Antônio Pereira</td>
    <td>RenGraminhani</td>
    <td>[email protected]</td>
  </tr>
  <tr>
    <td>CAVALEIROS DA LUZ</td>
    <td>CAR CESAR TANURI</td>
    <td>caranuri.com</td>
  </tr>
</table>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.