How to remove Level 1 keys using only one Callback method

Asked

Viewed 31 times

2

I don’t want to use foreach and neither for. For example, I have the following array structure:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [id_usuario] => 1
                )

            [1] => Array
                (
                    [idade] => 21
                )
        )
    [1] => Array
         (
            [0] => Array
                (
                    [id_usuario] => 2
                )

            [1] => Array
                (
                    [idade] => 15
                )
         )
)

But I would like my array to look like this:

 Array
    (
        [0] => Array
            (
                [id_usuario] => 1                       
                [idade] => 21
            )
        [1] => Array
            (
               [id_usuario] => 2
               [idade] => 15
            )
    )

Obs: I don’t want anything like that either:

foreach ($items as list($var1, $var2, $var3)) {
    if ($var1 == $var2) {
        echo $var3;
    }
}

The goal is to improve the structure.

2 answers

1

How do not want to use conditions, considering its fixed array structure, array_merge resolve, it merges one or more arrays.

$teste = Array(
            Array(
                Array('id_usuario' => 1),
                Array('idade' => 21)),
            Array(
                Array('id_usuario' => 2),
                Array('idade' => 15)));

$r[0] = array_merge($teste[0][0], $teste[0][1]);
$r[1] = array_merge($teste[1][0], $teste[1][1]);

print_r($r);

0


I managed to do so:

$myarray = array(
            array(
                array('id_usuario' => 1),
                array('idade' => 21)
                ),
            array(
                array('id_usuario' => 2),
                array('idade' => 15)
                )
         );
$data =  array_map(function($arr) {
                 return array_merge($arr[0],$arr[1]);
}, $myarray);

echo '<pre>';
print_r($data);

Browser other questions tagged

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