How to convert two single dimensional arrays into one multi-dimensional array – PHP

Here is my code where I took post values in an array and separate them into 2 single dimensional arrays i.e. even numbers and odd numbers.

    $seed_pairing = $this->input->post('seed');
    if ($seed_pairing) {
        $even_array = array();
        for ($i = 0; $i = count($seed_pairing); $i++) {
            if ($i % 2 == 0 && $i != 0) {
                $even_array[] = $i;
            }
        }
        $odd_array = array();
        for ($i = 0; $i = count($seed_pairing); $i++) {
            if ($i % 2 !== 0 && $i != 0) {
                $odd_array[] = $i;
            }
        }
        rsort($even_array);
        print_r($odd_array);
        print_r($even_array);die();
    }

Above code is working perfectly and exactly what I want, here is the result of current arrays. Now I want to pair them together like in the multi-dimensional array given below.

    Array
    (
        [0] => 1
        [1] => 3
    )
    Array
    (
        [0] => 4
        [1] => 2
    )

This is what i want

    Array
    (
        [0] => Array
            (
                [0] => 1
                [1] => 4
            )
        [1] => Array
            (
                [0] => 3
                [1] => 2
            )
    )

Answer

$new_array = [];

foreach ($even_array as $key => $value) {
    $new_array[] = [$even_array[$key], $odd_array[$key]];
}

print_r($new_array);

###result:

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

    [1] => Array
        (
            [0] => 2
            [1] => 3
        )

)

Leave a Reply

Your email address will not be published. Required fields are marked *