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
        )

)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.