Home > front end >  Walk every key for each array in a multidimensional array
Walk every key for each array in a multidimensional array

Time:10-01

I have an algorithm issue I can't manage to complete. Let's take the following example :

$array['toto'][] = rand(0,10);
$array['toto'][] = rand(0,10);
$array['toto'][] = rand(0,10);

$array['titi'][] = rand(0,10);
$array['titi'][] = rand(0,10);

$array['other'][] = rand(0,10);
$array['another'][] = rand(0,10);

// let's do a var_dump
array(4) {
  ["toto"]=>array(3) {[0]=> int(4),[1]=> int(5),[2]=> int(3)}
  ["titi"]=>  array(2) {[0]=> int(9), [1]=> int(7)}
  ["other"]=> array(1) {[0]=> int(9)}
  ["another"]=> array(1) {[0]=> int(6)}
}

The thing I'm trying to achieve is to sum every value for each array once. It's a bit hard to explain, the final combination is :

toto[0]   titi[0]   other[0]   another[0] = ...
toto[1]   titi[0]   other[0]   another[0] = ...
toto[2]   titi[0]   other[0]   another[0] = ...
toto[0]   titi[1]   other[0]   another[0] = ...
toto[1]   titi[1]   other[0]   another[0] = ...
toto[2]   titi[1]   other[0]   another[0] = ...

Of course "other", "another" could be an array of more elements and the combinations would be multiplied. All array could be of size 1 or all array of size > 1 or a mix or both like the example.

I can't manage in PHP to write a code that would create this algorithm.

Any help would be greatly appreciated ! Thank you,

CodePudding user response:

Ideally store titi, toto etc in separate arrays instead of a single array. Then loop through the each array using for loops. Then it would be much easier to do. Without proper data structures everything becomes a difficult problem.

CodePudding user response:

Thank you for answering people.

Indeed I didn't know (or could remember) the concept of Cartesian Product. It's exactly what I needed !

Again thanks =)

CodePudding user response:

What is it exactly what you want to achieve?

You wrote:

It's a bit hard to explain, the final combination is :

I think what you are looking for is called permutations. That is every possible combination. In your case you want the sums of every permutation. <-- And I am wrong.

EDIT: Cartesian Product is what you need, as Dillon Davis pointed out.

Cartesian Products

A Cartesian Product is defined on an ordered set of sets. It is the set of all possible ordered combinations consisting of one member from each of those sets.

Here is a more in-depth explanation:

https://www.sciencedirect.com/topics/computer-science/cartesian-product

So my original advice was wrong:

https://en.wikipedia.org/wiki/Permutation <-- don't use this

  • Related