Essiw Sined
Essiw Sined

Reputation: 89

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.

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.

    array
  'math' => 
    array 
      'paper 1' => 50
      'paper 2' => 70
      'paper 3' => 80      
  'Sci' => 
    array 
     'paper 1' => 50
      'paper 2' => 70
      'paper 3' => 80

Upvotes: 0

Views: 197

Answers (2)

Barmar
Barmar

Reputation: 781751

The approach using built-in functions that Scuzzy posted is nice. 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.

Upvotes: 1

Scuzzy
Scuzzy

Reputation: 12332

$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

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.

Upvotes: 2

Related Questions