John Davidson

php - Generate uniq data recursively (all combinations) from source array

0 comments
Message:


I have source data array like this:


$data = [
'A' => 'test',
'B' => [1, 2],
'C' => [3, 4],
];

There can be different number of keys. In the example we have 3. The value of every key can be array or string.


Now I need to generate from this array the new one (using keys from source array) like this:


$newData = [
0 => [
'A' => 'test',
'B' => 1,
'C' => 3,
],
1 => [
'A' => 'test',
'B' => 1,
'C' => 4,
],
2 => [
'A' => 'test',
'B' => 2,
'C' => 3,
],
3 => [
'A' => 'test',
'B' => 2,
'C' => 4,
],
];

Start implementing the solution but maybe someone have something similar.



My Answer:
> 'B',
> 'C',
> 'D'
];

To generate all unique combinations recursively, you can use the following PHP code:

php
function generateCombinations($data, $prefix = []) {
$combinations = [];

foreach ($data as $key => $value) {
$newPrefix = array_merge($prefix, [$key => $value]);
$combinations[] = $newPrefix;

$remainingData = array_diff_key($data, $newPrefix);
$combinations = array_merge($combinations, generateCombinations($remainingData, $newPrefix));
}

return $combinations;
}

$data = [
'A' => 'B',
'C',
'D'
];

$combinations = generateCombinations($data);

foreach ($combinations as $combination) {
echo implode(', ', $combination) . "\n";
}


This code defines a recursive function `generateCombinations` that generates all unique combinations of the source data array. It iterates over each element in the data array, adding it to the current prefix and recursively calling itself with the remaining data. The function returns an array of all unique combinations.

You can then call the function with your source data array and iterate over the generated combinations to display them.

Rate this post

5 of 5 based on 9016 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us