foreach with multiple variables

1

I'm trying a foreach with several variables got like?

$record = array();  
foreach($resultCustomers as $group)
{
    $record[$group['CODIGO_CLIENTE'].$group['RAZAOSOCIAL']][] = $group['NOME'];


}   

$output = array();  

foreach( $record as $id => $name)
{
    $output[] = array(
            'CODIGO_CLIENTE' => $id,
            'RAZAOSOCIAL' => $id,
            'NOME' => $name
    );

}

It's coming out like this:

array (size=3)
  'CODIGO_CLIENTE' => string '1Empresa S/A' (length=38)
  'RAZAOSOCIAL' => string '1Empresa S/A' (length=38)
  'NOME' => 
    array (size=23)
      0 => string 'Cliente 1' (length=23)
      1 => string 'Cliente 2' (length=31)
      2 => string 'Cliente 3' (length=43)
      3 => string 'Cliente 4' (length=26)
      4 => string 'Cliente 5' (length=29)
      5 => string 'Cliente 6' (length=21)

I needed a return like this:

array (size=3)
  'CODIGO_CLIENTE' => string '1' (length=38)
  'RAZAOSOCIAL' => string 'Empresa S/A' (length=38)
  'NOME' => 
    array (size=23)
      0 => string 'Cliente 1' (length=23)
      1 => string 'Cliente 2' (length=31)
      2 => string 'Cliente 3' (length=43)
      3 => string 'Cliente 4' (length=26)
      4 => string 'Cliente 5' (length=29)
      5 => string 'Cliente 6' (length=21)

Does anyone have an idea? Thank you!

    
asked by anonymous 11.07.2016 / 21:59

1 answer

1

You are creating the key different from what you need. Instead of creating $ record as you are generating, try:

$record = array();  
foreach($resultCustomers as $group) {
    $record[$group['CODIGO_CLIENTE']]['RAZAOSOCIAL'] = $group['RAZAOSOCIAL'];
    $record[$group['CODIGO_CLIENTE']]['nomes'][] = $group['NOME'];
}   

and retrieve the data as follows:

foreach( $record as $id => $dados) {
    $output[] = array(
            'CODIGO_CLIENTE' => $id,
            'RAZAOSOCIAL' => $dados['RAZAOSOCIAL'],
            'NOME' => $dados['nomes']
    );
}
    
11.07.2016 / 22:13