简体   繁体   中英

How to get array combinations in php?

I have a array in php

array(100,125,135);

I would like to know How I can get all combinations like in the below EG ?

Eg:100=>125,100=>135,125=>100,125=>135,135=>100,135=>125

I Tried something like this

$selected_items = array(100,125,135);
$total = count($selected_items);
$combination = array();
$newcom=0;
    for($i=0;$i<$total;$i++){           
        if($newcom <= $total-1) $newcom = $newcom-1;
        echo  $newcom."-----";
         $combination[$i] = array($selected_items[$i]=> $selected_items[$newcom]);
            $newcom = $i+1;  
    }

But this is not working to get all combinations

Please help me.

Try this

$temp = array(1, 2, 3);
$result = array();

foreach ($temp as $value)
{
    foreach ($temp as $value2)
    {
       if ($value != $value2) $result[$value] = $value2;
    }
}
$a = array(100,125,135);
$output = array();
foreach ($a as  $first) {
    $arr[$first]=array();
    foreach ($a as $second) {
        if($first != $second)
            $arr[$first][] = $second;
    }

}
$output = $arr;
print_r($output);

You could use a couple of foreach loops -

$sequence     = [100, 125, 135];
$permutations = [];

foreach ($sequence as $value) {
    foreach ($sequence as $value2) {
        if ($value != $value2) {
            $permutations[] = [$value => $value2];
        }
    }
}

I don't think this can be done. An array contains a key and a value. In your example you want an array where the keys can be the same. You will just overwrite your values So if you run your example the result will be somthing like the following:

 100=>135
,125=>135
,135=>125

A possible solution can be multidimensional arrays:

 100=>array(125, 135)
,125=>array(100, 135)
,135=>array(100, 125)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM