繁体   English   中英

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

[英]How to associate values from one array to another array as keys?

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

数组1:

Array
(
    [0] => id
    [1] => name
    [2] => email
)

数组2:

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
)

如何将Array1中的值作为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
)

您可以在步骤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]; 
  }

我会使用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM