如何将一个数组中的值作为键与另一个数组相关联?

时间:2018-04-01 16:33:38

标签: php arrays

所以,简单地说,它看起来像这样:

数组1:

Array
(
    [0] => 1
    [1] => paula
    [2] => paula@paula.com

    [3] => 2
    [4] => martin
    [5] => martin@google.com

    [6] => 3
    [7] => kasandra
    [8] => kasandra@google.com

    [9] => 4
    [10] => helena
    [11] => helena@google.com

    [12] => 5
    [13] => sophia
    [14] => sophia@google.com

    [15] => 6
    [16] => denis
    [17] => denis@google.com
)

ARRAY2:

Array
(
    [id] => 1
    [name] => paula
    [email] => paula@paula.com

    [id] => 2
    [name] => martin
    [email] => martin@google.com

    [id] => 3
    [name] => kasandra
    [email] => kasandra@google.com

    [id] => 4
    [name] => helena
    [email] => helena@google.com

    [id] => 5
    [name] => sophia
    [email] => sophia@google.com

    [id] => 6
    [name] => denis
    [email] => denis@google.com
)

如何将Array1中的值作为Array2中的键进行相应处理,以使最终结果如下所示:

{{1}}

2 个答案:

答案 0 :(得分:2)

你可以在第3步使用for循环

  $numCoords  = count($array2)/3
  for ($i = 0; $i < $numCoords; $i++ ){
    $array[$i]['id'] = $array2[$i*3]; 
    $array[$i]['name'] = $array2[($i*3)+1]; 
    $array[$i]['email'] = $array2[($i*3)+2]; 
  }

答案 1 :(得分:1)

我会选择array_chunk并习惯于数字索引, 但如果你真的想把它们作为单词,你可以映射它们:

$keys = [
    0 => 'id',
    1 => 'name',
    2 => 'email'
];

$chunked = array_chunk($array2, $length=3);
$result = array_map(function ($chunk) {
    global $keys;
    return array_combine($keys, $chunk);
}, $chunked);