每第n个具有新键名的键将一维键值数组转换为二维键值数组

我有一个看起来像这样的数组:

enter image description here

我需要将其翻译为:

enter image description here

Some things to know about the $startArray is that it is dynamic based on the amount of people submitted on a form. Each person always has just those three fields though (custom_12, custom_13, custom_14 aka fName, lName, email). So if there were 5 members, the 5th members fName would be the key custom_12-5 in the start array.

I've been looking around on stackoverflow for a question just like this and I was not able to find one. What would be the steps taken and possible array functions or anything else for creating the $endArray ?

评论
  • siusto
    siusto 回复

    There's actually a builtin function for this: https://www.php.net/manual/en/function.array-chunk.php

    For example, array_chunk($startArray, 3) will give you the base for your new array, you'll just need to then iterate through it and rename the keys.

    另外,您可以自己遍历数组,然后根据当前迭代的索引将值添加到新数组中。

  • O老男人
    O老男人 回复

    感谢查理的建议,我想到了这一点。

    $startArray = array(
        'custom_12' => 'john',
        'custom_13' => 'johny',
        'custom_14' => 'john@johny.com',
        'custom_12-2' => 'bob',
        'custom_13-2' => 'bobby',
        'custom_14-2' => 'bob@bobby.com',
        'custom_12-3' => 'don',
        'custom_13-3' => 'donny',
        'custom_14-3' => 'don@donny.com'
    );
    
    $middleArray = array_chunk($startArray, 3);
    
    $endArray = array_map(function($val) {
        return array(
            'fName' => $val[0],
            'lName' => $val[1],
            'email' => $val[2]
        ); 
    }, $middleArray);
    
    echo "<pre>";
        print_r($endArray);
    echo "</pre>";
    

    输出正是我想要的:

    enter image description here