3

I am not sure how to exactly explain what I am trying to do but I try to explain using an example.

$products = array("35","37","43");

Say if I have above array how can I create a result array that will look like this.

$related_products = array (

array (35,37),

array (35,43),

array (37,35),

array (37.43),

array (43,35),

array (43, 37) )

2 Answers 2

5

You could use two loops to catch all combinations:

$products = array("35","37","43");
$result = array();
for($i = 0; $i < count($products); $i++) {
    for($j = 0; $j < count($products); $j++) {
        if($i !== $j) {
            $result[] = array(
                $products[$i],
                $products[$j]
            );
        }   
    }
}

print_r($result);

Result:

Array
(
    [0] => Array
        (
            [0] => 35
            [1] => 37
        )

    [1] => Array
        (
            [0] => 35
            [1] => 43
        )

    [2] => Array
        (
            [0] => 37
            [1] => 35
        )

    [3] => Array
        (
            [0] => 37
            [1] => 43
        )

    [4] => Array
        (
            [0] => 43
            [1] => 35
        )

    [5] => Array
        (
            [0] => 43
            [1] => 37
        )

)
0
0

You can simply add one item to main array using array_push method like this,

$products = array("35","37","43");
$data = array();
for($i = 0; $i < count($products); $i++) {
    for($j = 0; $j < count($products); $j++) {
        if($i !== $j) {
              array_push($data,array($products[$i],$products[$j]));
            );
        }   
    }
}

print_r($data);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.