PHP-将数组值组合为两个唯一的对
我正在尝试转换以下数组PHP-将数组值组合为两个唯一的对,php,arrays,combinations,permutation,Php,Arrays,Combinations,Permutation,我正在尝试转换以下数组 Array ( [304] => Array ( [0] => 102 [1] => 177 [2] => 132 [3] => 223 ) [302] => Array (
Array
(
[304] => Array
(
[0] => 102
[1] => 177
[2] => 132
[3] => 223
)
[302] => Array
(
[0] => 132
[1] => 96
)
)
具体如下:
Array
(
[0] => Array
(
["source"] => 102
["target"] => 177
)
[1] => Array
(
["source"] => 102
["target"] => 132
)
[2] => Array
(
["source"] => 102
["target"] => 223
)
[3] => Array
(
["source"] => 177
["target"] => 132
)
[4] => Array
(
["source"] => 177
["target"] => 223
)
[4] => Array
(
["source"] => 132
["target"] => 223
)
// only two values, so just one pair
[5] => Array
(
["source"] => 132
["target"] => 96
)
)
所以我得到了所有可能的配对,没有任何重复
我尝试了很多东西,比如带if语句的循环中的循环,但我不知道从哪里开始。。。
例如:
$new_links = array();
foreach($arr as $arr_new){
foreach($arr_new as $key => $value){
if($key == 0){
$source=$value;
}else{
$new_links[$key]["source"]=$source;
$new_links[$key]["target"]=$value;
}
}
}
其中$arr是给定的数组
所以我的问题是:实现这一目标最有效的方法是什么
提前谢谢
---编辑---
多亏了
我只需要编辑一点语法就可以让它运行,但是逻辑工作起来很有魅力
我的最终结果是:
// the given array is $arr
$result = array();
foreach ($arr as $group)
{
$lastIdx = count($group) - 1;
$startIdx = 1;
foreach ($group as $member)
{
for ($pos = $startIdx; $pos <= $lastIdx; $pos++)
{
$result[] = array(
'source' => $member,
'target' => $group[$pos]
);
}
$startIdx++;
}
}
我试了很多东西。向我们展示。阅读相关主题。可能重复的尝试使用多维array@mickmackusa不知道该解释什么。。所以添加了评论。谢谢。为解决方案添加解释可以做很多伟大的事情。1.提高未来回答的文化预期标准。2.在教育/授权OP和未来研究人员方面做得很好。3.使使用现有页面作为资源关闭新的重复问题更有帮助。4.提高您赢得更多选票的可能性。5.使StackOverflow成为所有人的最佳资源。。。再次感谢您抽出时间。请永远带着教育的意图回答。
<?php
$input = [[102,177,132,223],[132,96]];
$result = [];
// for each group of elements in input array
foreach ($input as $group)
{
// set the first target element of the group to be
// second element
$nextTargetIdx = 1;
// determine last target index beforehand
// so that value gets computed only once per group
$lastTargetIdx = count($group) - 1;
// then, take each element of that group as source
foreach ($group as $source)
{
// and
for // every next element
(
$targetIdx = $nextTargetIdx;
$targetIdx <= $lastTargetIdx;
$targetIdx++
)
{
// add new result entry
$result[] = [
// with current source
'source' => $source,
// and target
'target' => $group[$targetIdx]
];
}
// then, when all targets for current source are found
// increase next target index so that it follows next source element
$nextTargetIdx++;
}
}
var_dump($result);