Filip  Busic Filip Busic - 5 months ago 15
PHP Question

Transforming three arrays to one with values/keys

Note: The arrays below are not 3 different arrays. They are part of 1 variable: $mainArray;

Sample Array 1 (Keys):

[0] => Apartments
[1] => Apartments
[2] => Apartments
[3] => Houses
[4] => Houses
[5] => Houses
[6] => Suites
[7] => Suites
[8] => Exclusive
[9] => Exclusive
[10] => SuperB


Sample Array 2 (Values):

[0] => Apartment Value1
[1] => Apartment Value2
[2] => Apartment Value3
[3] => Houses Value 1
[4] => Houses Value 2
[5] => Houses Value 3
[6] => Suites Value 1
[7] => Suites Value 2
[8] => Exclusive Value 1
[9] => Exclusive Value 2
[10] => SuperB Value 1


Sample Array 3 (Values):

[0] => Apartment Value1
[1] => Apartment Value2
[2] => Apartment Value3
[3] => Houses Value 1
[4] => Houses Value 2
[5] => Houses Value 3
[6] => Suites Value 1
[7] => Suites Value 2
[8] => Exclusive Value 1
[9] => Exclusive Value 2
[10] => SuperB Value 1


My desired result is:

$array[$key] = array($array2,$array3);


Sample Result:

[Apartments] => array(rows 0-3 from Array #2, 0-3 from Array #3);
[Houses] => array(rows 3-5 from Array #2, 3-5 from Array #3);
[Exclusive] => array(rows 6-7 from Array #2, 6-7 from Array #3);
[Suites] => array(rows 8-9 from Array #2, 8-9 from Array #3);
[SuperB] => array(row 10 from Array #2, 10 from Array #3);


Therefore becoming a dimensional array with keys.

For this question, lets always assume that the three arrays hold exactly the same amount of rows. The difference is, I want to transform the first array (keys), to hold the other two arrays as a dimensional array.

Answer

I think this is what you desire. Let me know if i can help you more about this.

<?php
    $mainArray = [
        ["Apartments","Apartments","Apartments","Houses","Houses","Houses","Suites","Suites","Exclusive","Exclusive","SuperB"],
        ["Apartment Value1","Apartment Value2","Apartment Value3","Houses Value 1","Houses Value 2","Houses Value 3","Suites Value 1","Suites Value 2","Exclusive Value 1","Exclusive Value 2","SuperB Value 1"],
        ["Apartment Value1","Apartment Value2","Apartment Value3","Houses Value 1","Houses Value 2","Houses Value 3","Suites Value 1","Suites Value 2","Exclusive Value 1","Exclusive Value 2","SuperB Value 1"]
    ];

    if(count($mainArray[0]) != count($mainArray[1]) || count($mainArray[0]) != count($mainArray[2])) {
        throw new Exception("Arrays are not the same size");
    }

    $resultArray = [];
    $count = count($mainArray[0]);

    for($i = 0; $i < $count; $i++) {
        if(!isset($resultArray[$mainArray[0][$i]])) {
            $resultArray[$mainArray[0][$i]] = array($mainArray[1][$i], $mainArray[2][$i]);
        } else {
            $resultArray[$mainArray[0][$i]][] = $mainArray[1][$i];
            $resultArray[$mainArray[0][$i]][] = $mainArray[2][$i];
        }
    }

    echo "<pre>".print_r($resultArray, true)."</pre>";
Comments