从1维创建二维数组

时间:2014-07-11 10:46:55

标签: php

如何从这个数组:

Array
(
    [0] => Array
        (
            [BLACK] => Array
                (
                    [0] => 3171
                    [1] => 3173
                    [2] => 3175
                )

            [WHITE] => Array
                (
                    [0] => 3170
                    [1] => 3172
                    [2] => 3174
                )

        )

    [1] => Array
        (
            [SMALL] => Array
                (
                    [0] => 3170
                    [1] => 3171
                )

            [MEDIUM] => Array
                (
                    [0] => 3172
                    [1] => 3173
                )

            [LARGE] => Array
                (
                    [0] => 3174
                    [1] => 3175
                )

        )

)

我可以创建这样的东西:

$array['BLACK']['SMALL'] = 3171;
$array['BLACK']['MEDIUM'] = 3173;
$array['BLACK']['LARGE'] = 3175;

$array['WHITE']['SMALL'] = 3170;
$array['WHITE']['MEDIUM'] = 3172;
$array['WHITE']['LARGE'] = 3174;

所以从1维创建二维数组,其中选项相同。

1 个答案:

答案 0 :(得分:0)

<?php
$colors = array('BLACK' => array('3171','3173','3175'),'WHITE' => array('3170','3172','3174'));
$sizes = array('SMALL' => array('3170','3171'),'MEDIUM' => array('3172','3173'), 'LARGE' => array('3174','3175'));

$merged = array();
foreach ($colors as $c_key => $color) {
foreach ($color as $c_val) {
    foreach ($sizes as $s_key => $size) {
    foreach ($size as $s_val) {
        if  ($c_val == $s_val) {
            $merged[$c_key][$s_key] = $c_val;       
        }
    }
    }
}
}
// var_dump($merged);
?>