PHP - Foreach auto tuning

Asked

Viewed 168 times

2

During development, it is often the case that 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 these data or even include more data 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 reallocate the value of $dadosUsuario[$k]

I’d have some way of making it more dynamic?

  • You can use methods such as array_walk(): http://php.net/manual/en/function.array-walk.php or array_walk_recursive() : http://php.net/manual/en/function.array-walk-recursive.php

2 answers

3


Yes would have, the passage 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’s Dice, i.e., it directly represents an adjustment itself $dadosUsuario[$k].

0

I don’t 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');
  • Sorry @Ivan, I don’t know if you understand the purpose of the question, but I just wanted to demonstrate that it is possible to pass by reference in the last element of the foreach. As for the code, I didn’t understand why you made one explode and implode and I can just pick it up $item['nome']. But thank you for participating.

Browser other questions tagged

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