在php中更改数组结构

时间:2015-11-24 14:37:47

标签: php arrays

如何在test2中更改test1数组格式?

$test1 = array(
    'size'=>array('V'=>array('V'),'R'=>array('R','R')),
    'price'=>array('V'=>array('77'),'R'=>array('88','99')),
    'unit'=>array('V'=>array('3'),'R'=>array('3','2')),
    'color'=>array('V'=>array('Black'),'R'=>array('Green','Red')));

$test2 = array(
    'size'=>array('V','R'),
    'price'=>array('V'=>array('Black'=>'77'),
                   'R'=>array('Green'=>'88','Red'=>'99')),
    'unit'=>array('V'=>array('Black'=>'3'),
                  'R'=>array('Green'=>'3','Red'=>'2')),
    'color'=>array('V'=>array('Black'),'R'=>array('Green','Red')));

谢谢!

2 个答案:

答案 0 :(得分:0)

使用foreach循环,您可以更改数组结构。 http://php.net/manual/de/control-structures.foreach.php 这样的东西应该有用:在你的情况下,很清楚从一个数组转换到另一个数组的规则是什么。

$test2 = array();
foreach ($test as $type => $array) {
    $newArray = array();
    foreach ($array as $key => $value) {
        if ($key == 'V') {
            if ($value == 3) {
                $newArray['V'] = array('Black' => 3);
            } else if ($value = 2) {
                $newArray['V'] = array('Green' => 2);
            }
        } else if ($key == 'R') {
            //....
        }
    }
    $test2[$type] = $newArray;
}

答案 1 :(得分:0)

感谢您的回复。抱歉没有更具体。实际上我想要动态的所有价值观。我构建了一个循环:)。谢谢!

$myArray = array();
foreach($test as $type => $array){
    $k = 0;
    foreach ($array as $key => $value) {
    if($type == 'size'){
        $myArray['size'][] = $key;
    }else if($type == 'price' || $type == 'unit' ){ 
        $m = 0;
        foreach($value as $vall){
            if($type == 'price'){
                $myArray['price'][$myArray['size'][$k]][$test['color'][$myArray['size'][$k]][$m]] = $test['price'][$myArray['size'][$k]][$m];
            }else if($type == 'unit'){
                $myArray['unit'][$myArray['size'][$k]][$test['color'][$myArray['size'][$k]][$m]] = $test['unit'][$myArray['size'][$k]][$m];
            }
            $m++;
        }
    }else if($type == 'color'){
        $myArray['color'][] = $value;
    }
    $k++;
}
}