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

时间:2021-09-18 01:39:04

So, to simply put it, it looks like this:

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

Array1:

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

Array2:

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
)

How to make those values from Array1 as keys in Array2 accordingly so that the end result looks like this:

如何将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
)

2 个解决方案

#1


2  

you can use a for loop with step 3

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

#2


1  

I would go with array_chunk and get used to numeric indexes, but if you really want to have them as words you may map them:

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

#1


2  

you can use a for loop with step 3

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

#2


1  

I would go with array_chunk and get used to numeric indexes, but if you really want to have them as words you may map them:

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