How to organize an array from a list

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
            )
    )
    
asked by anonymous 24.02.2017 / 19:44

1 answer

8

Starting from the principle that we know the keys beforehand:

$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 in $new :

DEMONSTRATION

In case you do not know the keys beforehand:

$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

    
24.02.2017 / 20:02