Search code examples
phparraysarray-map

Create an associative array using another array as keys


I currently have the $keys array

array(5) {
  [0] =>
  string(9) "SessionID"
  [1] =>
  string(5) "Title"
  [2] =>
  string(11) "Description"
  [3] =>
  string(5) "Level"
  [4] =>
  string(4) "Type"
}
that I use as keys for the values of another array called $values.

I would like to make an associative array by mapping the other array to $keys.

Another way to say this is I would like to array_combine($keys, $values) whereas $keys has only 5 elements but $values has more than 3000 elements.

Edit 1: Sorry for not putting in a $values example. It would have the same order as the $keys:

+-----------+-------+-------------+---------+------+
| SESSIONID | TITLE | DESCRIPTION |  LEVEL  | TYPE |
+-----------+-------+-------------+---------+------+
|           |       |             |         |      |
| 1         | A     | Describe A  | Level 1 | Word |
|           |       |             |         |      |
| 2         | B     | Describe B  | Level 2 | Word |
+-----------+-------+-------------+---------+------+

or

$values = [
1, 'A', 'Describe A', 'Level 1', 'Word',
2, 'B', 'Describe B', 'Level 2', 'Word'
];

since I populate both arrays from a single CSV file.


Solution

  • Since you've left out an explanation of what $values is I've guessed a little. Here are two scenarios.

    If your values are all at the same level like below, we can chunk them up:

    $keys = [ "SessionID", "Title", "Description", "Level", "Type", ];
    $values = [
        1,
        "Title A",
        "Desc A",
        "Monster",
        "car",
        2,
        "Title B",
        "Desc B",
        "Devil",
        "car",
    ];
    

    Cut the data up in to arrays with length equal to the number of keys.

    $chunks = array_chunk($values, count($keys));
    

    Then map them using array_combine like you suggested.

    $ass = array_map(function ($chunk) use ($keys) {
        return array_combine($keys, $chunk);
    }, $chunks);
    

    If your array is an array of arrays (or rows) we can skip the chunking part and pass it to the mapping function directly:

    $values = [
        [ 1, "Title A", "Desc A", "Monster", "car" ],
        [ 2, "Title B", "Desc B", "Devil", "car" ]
    ];
    
    $ass = array_map(function ($chunk) use ($keys) {
        return array_combine($keys, $chunk);
    }, $values);