【发布时间】:2016-08-17 15:08:55
【问题描述】:
我需要帮助来编写一个拆分这种数组的函数:
array (size=2)
seller1 =>
array (size=2)
0 => product1
1 => product2
seller2 =>
array (size=2)
0 => product1
1 => product3
对于所有没有相交值的可能组合,对于这个必须导致两个数组的示例:
array (size=2)
seller1 =>
array (size=1)
0 => product2
seller2 =>
array (size=2)
0 => product1
1 => product3
array (size=2)
seller1 =>
array (size=2)
0 => product1
1 => product2
seller2 =>
array (size=1)
0 => product3
困难在于必须适用于任意数量的子数组和任意数量的值(产品)。
这里我的功能缺少部分评论:
/**
* @param array $offersDataset
* @param array $productsIds
* @param int $sellers
* @param array $previous
*
* @return array
*/
private function getCombinations($offersDataset, $productsIds, $sellers, $previous = array())
{
$combinations = array();
foreach ($offersDataset as $sellerId => $products) {
if (false !== in_array($sellerId, array_keys($previous))) {
continue;
}
$current = array($sellerId => $products);
$total = $current + $previous;
$remainingSellers = $sellers - 1;
if ($remainingSellers > 0) {
$deeper = $this->getCombinations($offersDataset, $productsIds, $remainingSellers, $total);
$combinations = array_merge($combinations, $deeper);
} else {
$merge = array();
foreach ($total as $satisfiable) {
$merge = array_unique(array_merge($merge, $satisfiable));
}
$diff = array_diff($productsIds, $merge);
if (empty($diff)) {
$intersect = call_user_func_array('array_intersect', $total);
//if (!empty($intersect)) {
// TODO
// HERE SPLIT TOTAL TO MULTIPLE ARRAYS
//} else {
$combinations[] = $total;
//}
}
}
}
return $combinations;
}
输入:
$productsIds = array('product1', 'product2', 'product3');
$offersDataset = array(
'seller1' => array('product1', 'product2'),
'seller2' => array('product1', 'product3')
);
$sellers = 2;
输出:
array (size=1)
0 =>
array (size=2)
seller1 =>
array (size=2)
0 => product1
1 => product2
seller2 =>
array (size=2)
0 => product1
1 => product3
如果您能帮助我,将不胜感激!
【问题讨论】:
-
我在帖子中添加了缺少部分的函数
标签: php arrays combinations