Home > Blockchain >  Assign a key to array and group it by name and email in one array
Assign a key to array and group it by name and email in one array

Time:10-21

Hi all I'm novice in PHP and I do not know if somebody can help me to how to solve this:

I have an array that look's like this:

array (size=6)
  0 => 'alexg'
  1 => 'benny'
  2 => 'shahar'
  3 => '[email protected]'
  4 => '[email protected]'
  5 => '[email protected]'

How do I make it to look like this (assign a key and group it by name and email in one array):

array (size=3)
  array (size=2)
    'USERLOGIN' => 'alexg'
    'EMAIL' => '[email protected]'
  array (size=2)
    'USERLOGIN' => 'benny'
    'EMAIL' => '[email protected]'
  array (size=2)
    'USERLOGIN' => 'shahar'
    'EMAIL' => '[email protected]'

Until now i achive this:

array (size=6)
  0 => 
    array (size=1)
      'USERLOGIN' => string 'benny'
  1 => 
    array (size=1)
      'USERLOGIN' => string 'alexg'
  2 => 
    array (size=1)
      'USERLOGIN' => string 'shahar'
  3 => 
    array (size=1)
      'EMAIL' => string '[email protected]'
  4 => 
    array (size=1)
      'EMAIL' => string '[email protected]'
  5 => 
    array (size=1)
      'EMAIL' => string '[email protected]'

Thank you in advance and I hope somebody could help me.

CodePudding user response:

You want to just create the array? You can do it like this:

$variableName = [
    [
        'USERLOGIN' => 'alexg',
        'EMAIL' => '[email protected]',
    ],
    [
        'USERLOGIN' => 'benny',
        'EMAIL' => '[email protected]',
    ],
    [
        'USERLOGIN' => 'shahar',
        'EMAIL' => '[email protected]',
    ],
];

CodePudding user response:

If your array will always be 1st half logins and 2nd half emails :

$array = ['alexg', 'benny', 'shahar', '[email protected]', '[email protected]', '[email protected]'];

$len = count($array);
$half = $len/2;
  
$usernames = array_slice($array, 0, $half);
$emails = array_slice($array, $half, $len);
$allUsers = [];
    
foreach($usernames as $username) {
    $myUser['USERLOGIN'] = $username;
    array_push($allUsers, $myUser);
}
foreach($emails as $key=>$email) {
    $allUsers[$key]['EMAIL'] = $email;
}

var_dump($allUsers);
  • Related