简体   繁体   English

如何在php中创建带有索引的多维数组?

[英]How to create a multidimensional array with indexes in php?

I know this question was asked before, but mine is slightly different. 我知道之前曾问过这个问题 ,但是我的稍有不同。 how can I include the index while creating a multidimensional array using a foreach. 使用foreach创建多维数组时,如何包含索引。

I have these array 我有这些阵列

$array1=["math","sci"]
$arry2=["paper 1", "paper 2", "paper 3"]
array3=[50, 70,80]

how can I create an array in this format using foreach loop. 如何使用foreach循环以这种格式创建数组。

    array
  'math' => 
    array 
      'paper 1' => 50
      'paper 2' => 70
      'paper 3' => 80      
  'Sci' => 
    array 
     'paper 1' => 50
      'paper 2' => 70
      'paper 3' => 80
$array1=["math","sci"];
$array2=["paper 1", "paper 2", "paper 3"];
$array3=[50, 70,80];

$array = array_fill_keys( $array1, array_combine( $array2, $array3 ) );

print_r( $array );

Is one apprach without the need for loops https://3v4l.org/Rigqk 是一种无需循环的方法https://3v4l.org/Rigqk

array_combine() takes and array of "keys" and array of "values" and build a single array, then array_fill_keys() takes an array of keys and fills it with the value. array_combine()获取“键”的数组和“ values”的数组,并构建单个数组,然后array_fill_keys()获取键的数组,并用值填充它。

The approach using built-in functions that Scuzzy posted is nice. Scuzzy发布的使用内置函数的方法很好。 If you want to see how to write it out in loops: 如果您想了解如何将其写成循环:

$inner = array();
foreach ($array2 as $i => $key2) {
    $inner[$key2] = $array3[$i];
}
$result = array();
foreach ($array1 as $key1) {
    $inner[$key1] = $inner;
}

Unlike the other question, there's no need to nest the loops, because you're assigning the same array to each element of the result. 与其他问题不同,由于您将相同的数组分配给结果的每个元素,因此无需嵌套循环。

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

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