Ataman
Ataman

Reputation: 2590

Assign one array to another as key in PHP

I have two arrays. One has group names the other one has group items. I want to assign group names as keys to the second array.

Example:

$array1 = array(
  0 => "A",
  1 => "B"
);

$array2 = array(
  0 => "a,b,c,d",
  1 => "e,f,g,h"
);

The second array should become:

$array3 = array(
  A => "a,b,c,d",
  B => "e,f,g,h"
);

How can i achieve this in PHP?

Thanks

Upvotes: 0

Views: 104

Answers (3)

rwendlinger
rwendlinger

Reputation: 16

would work like this:

    <?php 
    $grpNames = array(0 => "A", 1 => "B");
    $grpItems = array(0 => "a,b,c,d", 1 => "e,f,g,h");
    $newArray = array();
        foreach($grpItems as $grpItemKey => $grpItems){
            if(isset($grpNames[$grpItemKey])){
                $newArray[$grpNames[$grpItemKey]] = $grpItems;
            }
        }

    var_dump($newArray);
     ?>

Upvotes: 0

Roger Guasch
Roger Guasch

Reputation: 410

you need to use array_combine, api here

Upvotes: 2

user4066167
user4066167

Reputation:

use array_combine as such :

$array2 = array_combine($array1, $array2);

Upvotes: 4

Related Questions