使用值/键

时间:2016-06-22 08:44:51

标签: php

注意:下面的数组不是3个不同的数组。它们是1变量的一部分:$ mainArray;

样本数组1(密钥):

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

样本数组2(值):

[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

样本数组3(值):

[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

我想要的结果是:

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

示例结果:

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

因此成为带键的维数组。

对于这个问题,我们总是假设这三个数组的行数完全相同。不同的是,我想转换第一个数组(键),将另外两个数组保存为维数组。

1 个答案:

答案 0 :(得分:0)

我认为这就是你想要的。如果我能为您提供更多帮助,请告诉我。

<?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>";