[英]PHP - Combine array values to unique pairs of two
我正在嘗試轉換以下數組
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 是給定的數組
所以我的問題是:實現這一目標的最有效方法是什么?
提前致謝!!
- - - 編輯 - - -
感謝chba !!
我只需要稍微編輯一下語法就可以讓它運行,但邏輯就像一個魅力!!
我的最終結果是:
// 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++;
}
}
<?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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.