phparraysarray-mergearray-combine

Combine One array to several array


I have following content:

$staticArray = ['group_1', 'group_2'];

foreach ($staticArray as $name){
    $names[] = $name;
}

$staticArray2 = ['one', 'two'];

$i = 0;
foreach ($staticArray2 as $name){

    $item['group']['name']   = $names;
    $item['group']['user_1']   = 'Peter';
    $item['group']['user_2'] = 'Jack';

    $groups[] = $item;

    $i++;
}

The above code output is like this:

[ {
group: {
    name: [
       "group_1",
       "group_2",
       "group_1",
       "group_2"
   ],
    user_1: "Peter",
    user_2: "Jack"
   }
},

{
group: {
   name: [
      "group_1",
      "group_2",
      "group_1",
      "group_2"
   ],
   user_1: "Peter",
   user_2: "Jack"
  }
} ]

How can I edit first code to look like this:

{
   group: {
      name: "group_1", //group 1
      user_1: "Peter",
      user_2: "Jack"
   },
   group: {
      name: "group_2", //group 2
      user_1: "Peter",
      user_2: "Jack"
   }
}

$staticArray and $staticArray2 is a two static variable, so these 2 items cannot be editable.

If you don't understand what I mean. Read this:

I have two array:

$legues = [ 'Laliga', 'Bundesliga', '...' ];

$teams  = [ 'FC Barcelona', 'RCD Mallorca', 'UD Levante', 'CF Valencia', 'FC Salzburg', 'WSG Tirol' ];

First league is "Laliga" and this league have 4 team: FC Barcelona , RCD Mallorca, UD Levante and CF Valencia.

Second league is "Bundesliga" and this league have 2 team: FC Salzburg and WSG Tirol.

Now I want to put this teams to the league (like my last output code).


Solution

  • Replace

    $item['group']['name']   = $names;
    

    with

    $item['group']['name']   = $names[$i];
    

    Example

    Note: lengths of these static arrays should be the same.

    This move

    $staticArray = ['group_1', 'group_2'];
    
    foreach ($staticArray as $name){
        $names[] = $name;
    }
    

    doesn't makes sense. Your $names array equal to $staticArray. So, you can use $staticArray instead of $names array.

    If you need to define a several values from $staticArray2 to the first one (4,2 etc.) you need to define support array, like [4,2] and create specific loop for filling data in the $groups.

    Demo

    Here $sup array should be the same length with $legues.