0

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
1
  • You sure you need the same paper/numbers repeating by subject? Commented Jul 13, 2018 at 22:41

2 Answers 2

2
$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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

thanks for the clarification, all what i had in my mind was to use a loop, but i will go with his solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.