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

• 85

``````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"
}
}
``````

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

##### 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));``````