Объединить значения массива в уникальные пары из двух

Я пытаюсь преобразовать следующий массив

    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++;
}
}

-2

Решение

<?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);
3

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector