Replace indexed keys in each row of a 2d array with a static word followed by an incremented counter

1k Views Asked by At

To save on typing out the key name for every single array, I want to be able to build lists like.

$lists = [
    ['A', 'B', 'C', 'D', 'E'],
    ['A', 'B', 'C', 'D', 'E'],
    ['A', 'B', 'C', 'D', 'E'],
];

and then assign the same key names to all them (either before or after)

Key1, Key2, Key3, Key4, Key5

so when they're called, I can do something like:

foreach ($lists as $list) {
    showList($list);
} 

and then within the showList() function, I can call the 5 keys by the key name.

The function I have set no problem, but it's assigning the key names that I'm not sure how to do.

From comment under @Barmar's answer:

I get the following error.. Warning: array_combine() [function.array-combine]: Both parameters should have an equal number of elements

In $lists, the element count does go up to 29. That's the only thing I can think of that doesn't match, but I thought it would see 5 keys for 5 values in each of the 29 arrays within $lists.

3

There are 3 best solutions below

0
On

Try this :

<?php
$keys = array('Key1', 'Key2', 'Key3', 'Key4', 'Key5');
$lists = array (
                    array ('A', 'B', 'C', 'D', 'E'),
                    array ('A', 'B', 'C', 'D', 'E'),
                    array ('A', 'B', 'C', 'D', 'E')
                );

function showList($list){
    global $keys;
    return array_combine($keys, $list);
}

$output = array_map("showList", $lists);

echo "<pre>";
print_r($output);
?>

Result:

Array
(
    [0] => Array
        (
            [Key1] => A
            [Key2] => B
            [Key3] => C
            [Key4] => D
            [Key5] => E
        )

    [1] => Array
        (
            [Key1] => A
            [Key2] => B
            [Key3] => C
            [Key4] => D
            [Key5] => E
        )

    [2] => Array
        (
            [Key1] => A
            [Key2] => B
            [Key3] => C
            [Key4] => D
            [Key5] => E
        )

)
4
On

array_combine will make an associative array from an array of keys and an array of values.

$keys = array('Key1', 'Key2', 'Key3', 'Key4', 'Key5');
foreach ($lists as $list) {
    showList(array_combine($keys, $list));
}

If you want to modify $lists permanently, you can do:

foreach ($lists as &$list) {
    $list = array_combine($keys, $list);
}

The reference variable &$list makes this replace the elements in place.

0
On

To accommodate an indeterminant amount of elements in rows, you can use a nested loop to iterate the rows and populate a temporary array with the desired calculated key names and then overwrite the original row after the nested loop is finished.

Code: (Demo)

$lists = [
    ['A', 'B', 'C', 'D', 'E'],
    ['A', 'B', 'C', 'D'],
    ['A', 'B', 'C', 'D', 'E', 'F'],
];

foreach ($lists as &$row) {
    $newRow = [];
    foreach ($row as $i => $v) {
        $newRow['Key' . $i + 1] = $v;
    }
    $row = $newRow;
}
var_export($lists);

In all honesty, I have never needed to add meaningless keys like this in a professional project. I have suspicions that this is an XY Problem; perhaps it is time to ask the larger question of "why" is this necessary.