0

I have a multidimensional array $elements where I need to fill it with values from the array $ratings. The array $ratings is built so the first value will fit into the first slot in elements, the next in the second and so on.

$elements
4 => array:3 [▼
  2 => 0
  3 => 0
  4 => 0
]

5 => array:3 [▼
  2 => 0
  3 => 0
  4 => 0
]

7 => array:3 [▼
  2 => 0
  3 => 0
  4 => 0
]

I now need to fill $elements with 9 specific values from

$ratings
array:9 [▼
0 => 3
1 => 2
2 => 1
3 => 3
4 => 3
5 => 2
6 => 3
7 => 2
8 => 1
9 => 3
]

If I manage to loop through $elements, inserting values from $ratings one by one, I will have solved my problem.

So $elements[4][2] should have the value of 3, $elements[4][3] should have value of 2 etc.

2 Answers 2

1

Also you can manipulate these by array_fill using loop.

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

1 Comment

can you add more information, including an example?
0

Try this:

<?php
$elements = [ 
    4=>[2=>0, 3=>0, 4=>0],
    5=>[2=>0, 3=>0, 4=>0],
    7=>[2=>0, 3=>0, 4=>0],
];

$ratings = [ 0 => 3, 1 => 2, 2 => 1, 3 => 3, 4 => 3, 5 => 2, 6 => 3, 7 => 2, 8 => 1, 9 => 3 ];

$ratingsIndex = 0;
foreach(array_keys($elements) as $ElementsIndex) {
    foreach(array_keys($elements[$ElementsIndex]) as $ElementsSubIndex) {
        $elements[$ElementsIndex][$ElementsSubIndex] = $ratings[$ratingsIndex++];
    }
}

echo "<pre>";
print_r($elements);
echo "</pre>";
?>

1 Comment

Thanks, but how would you do this if the keys for the $elements array can different each time? As a more dynamic 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.