PHP - Foreach self-tuning

2

During development, there are many times when a request is made to the database, in which the returned data comes in array, sometimes it is necessary to perform a foreach to adjust this data or even include more data of according to a specific data.

Example:

$dadosUsuario = $this->UsuarioModel->getDados('all');

foreach($dadosUsuario as $k => $dadoUsuario){

    $nome = $dadoUsuario['name'];
    $lastName = $dadoUsuario['name'];

    $fullName = sprintf('%s %s', $name, $lastName);

    $dadoUsuario['fullName'] = $fullName;

    $dadosUsuario[$k] = $dadoUsuario;
}

Note that it was necessary to reassign the value of $dadosUsuario[$k]

Would you have some way to make this more dynamic?

    
asked by anonymous 18.09.2015 / 19:24

2 answers

3

Yes it would , passing by reference &

Example:

foreach($dadosUsuario as $k => &$dadoUsuario){

    $nome = $dadoUsuario['name'];
    $lastName = $dadoUsuario['name'];

    $fullName = sprintf('%s %s', $name, $lastName);

    $dadoUsuario['fullName'] = $fullName;
}

Note, the & in $dadoUsuario , so the variable points directly to the array index, ie it directly represents an adjustment in $dadosUsuario[$k] itself.     

18.09.2015 / 19:25
0

I do not know exactly what you want to do, but here's an example:

$dadoUsuario = array('... vem os dados do banco');


function getDadosUsuario($item, $key)
{
  $parseNames = explode(' ',$item['nome']);
   $fullName = $item['nome'];
   $fistName = $parseNames[0];
   $lastName = $parseNames[1];
   unset($names[0]); 
   $lastNameComplete = implode(' ',$parseNames); 

    $dadoUsuario[$key] = array(
         'nome_completo'      => $fullName,
         'nome'               => $fistName,
         'sobrenome'          => $lastName 
         'sobrenome_completo' => $lastNameComplete
   );

}

array_walk_recursive($dadosUsuario, 'getDadosUsuario');
    
18.09.2015 / 20:18