求PHP的多维数组嵌套遍历指定格式的算法

有一个二维数组

array(2) {
  ["尺寸"]=>
  array(2) {
    [0]=>
    string(3) "Big"
    [1]=>
    string(5) "small"
  }
  ["颜色"]=>
  array(2) {
    [0]=>
    string(6) "yellow"
    [1]=>
    string(3) "red"
  }
   ["高度"]=>
  array(2) {
    [0]=>
    string(6) "100"
    [1]=>
    string(3) "50"
  }
}

需要实现一个遍历每个key出一个元素,这里面的规格可能有很多,比如颜色尺寸长度等等, 然后组成一个新的包含所有组合的排列

 [
 [
    颜色:'yellow',
    尺寸:"Big",
    高度 :'100',
 ],
 [
    颜色:'yellow',
    尺寸:"red",
    高度 :'100',
 ], [
    颜色:'yellow',
    尺寸:"small",
    高度 :'',
 ], [
    颜色:'red',
    尺寸:"small",
    高度 :'',
 ],
 ]
 

大概这种数组格式,所以求一个算法,现在我是只能遍历拼接但是做不来数组。

阅读 2k
2 个回答
// 格式化数据
function format($data) {
    $keys = array_keys($data);
    $values = array_values($data);

    $result = [];
    foreach(Descartes($values) as $item) {
        foreach($item as $index => $row) {
            foreach($keys as $key) {
                if (in_array($row, $data[$key])) {
                    $item[$key] = $row;
                    unset($item[$index]);
                    break;
                }
            }
        }
        $result[] = $item;
    }

    return $result;
}

// 计算笛卡尔积
function Descartes($data) {
    $result = array_chunk(array_shift($data), 1);
    do {
        $temp = array();
        $next = array_shift($data);
        foreach($result as $first) {
            foreach(array_chunk($next, 1) as $second) {
                $temp[] = array_merge($first, $second);
            }
        }
        $result = $temp;
    } while($data);

    return $result;
}

$data = [
    '尺寸' => ['Big', 'small'],
    '颜色' => ['yellow', 'red'],
    '高度' => ['100', '50'],
];
print_r(format($data));

<?php

$color = array("red","yellow");
$size = array("big","small");

$data = array();

for($i = 0; $i < count($color); $i++){
    for($j = 0; $j < count($size); $j++){
        array_push($data, "{color:'" . $color[$i] . "', size: '" . $size[$j] . "'}");
    }
}

for ($i=0; $i < count($data); $i++) { 
    echo $data[$i];
}

?>

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题