How to organize an array of a list

Asked

Viewed 168 times

3

An array that looks like this:

Array
    (
        [nome_e_sobrenome] => Array
            (
                [0] => Luiz Felipe Machado
                [1] => Maria Rita de Cássia
            )

        [usuario] => Array
            (
                [0] => luizf
                [1] => mariar
            )

        [senha] => Array
            (
                [0] => XXXX
                [1] => YYYY
            )

    )

Stay like this:

  Array
    (
        [0] => Array
            (
                [nome_e_sobrenome] => Luiz Felipe Machado
                [usuario] => luizf
                [senha] => XXX
            )

        [1] => Array
            (
                [nome_e_sobrenome] => Maria Rita de Cássia
                [usuario] => mariar
                [senha] => YYY
            )
    )
  • 2

    Have you tried anything? Some code, something?!

  • I’m still trying to...

1 answer

8


From the beginning we know the ante-hand keys:

$original = array(
    'nome_e_sobrenome' => array(
        'Luiz Felipe Machado',
        'Maria Rita de Cássia'  
    ),
    'usuario' => array(
        'luizf',
        'mariar'
    ),
    'senha' => array(
        'XXX',
        'YYYY'
    ),
);

$new = array();
foreach($original['nome_e_sobrenome'] as $pos => $val) {
    $new[] = array(
        'nome_e_sobrenome' => $original['nome_e_sobrenome'][$pos],
        'usuario' => $original['usuario'][$pos],
        'senha' => $original['senha'][$pos],
    );
}

The new format will now be on $new:

DEMONSTRATION

In case you don’t know the ante-hand keys:

$original = array(
    'nome_e_sobrenome' => array(
        'Luiz Felipe Machado',
        'Maria Rita de Cássia'  
    ),
    'usuario' => array(
        'luizf',
        'mariar',
    ),
    'senha' => array(
        'XXX',
        'YYYY'
    ),
);

$new = array();
foreach($original as $key => $val) {
    foreach($val as $idx => $dado) {
        $new[$idx][$key] = $dado;
    }
}

DEMONSTRATION

  • 1

    Wow, I was coming up with an answer just like yours :)

  • hehehe @jlHertel :P

  • Not only that, the values and keys will be dynamic.

  • @Ivanferrer, I edited for this possibility too, is the second example

  • The second example worked perfect, thanks!

Browser other questions tagged

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