【发布时间】:2023-03-31 01:04:01
【问题描述】:
我需要使用从数组中获取的值创建路径结构:
Array
(
[machineAttribute] => Array
(
[0] => TTT 1000 S
[1] => TTT 1100 S
)
[technicalAttribute] => Array
(
[0] => Certificate
[1] => Software
)
[languageAttribute] => Array
(
[0] => English
[1] => Spanish
)
)
所以,我需要创建如下所示的路径:
Array
(
[0] => TTT 1000 S/Certificate/English
[1] => TTT 1000 S/Certificate/Spanish
[2] => TTT 1000 S/Software/English
[3] => TTT 1000 S/Software/Spanish
[4] => TTT 1100 S/Certificate/English
[5] => TTT 1100 S/Certificate/Spanish
[6] => TTT 1100 S/Software/English
[7] => TTT 1100 S/Software/Spanish
)
这是一个完美的场景,我能够使用嵌套的 foreach 解决这个问题:
if (is_array($machineAttributePath))
{
foreach ($machineAttributePath as $machinePath)
{
if (is_array($technicalAttributePath))
{
foreach ($technicalAttributePath as $technicalPath)
{
if (is_array($languageAttributePath))
{
foreach ($languageAttributePath as $languagePath)
{
$multipleMachineValuesPath[] = $machinePath . '/' . $technicalPath . '/' . $languagePath);
}
}
}
}
}
return $multipleMachineValuesPath;
}
但是,问题开始了,如果数组返回混合值,有时返回单个值,有时返回数组。例如:
Array
(
[machineAttribute] => Array
(
[0] => TTT 1000 S
[1] => TTT 1100 S
[2] => TTT 1200 S
)
[technicalAttribute] => Certificate
[languageAttribute] => Array
(
[0] => English
[1] => Spanish
)
)
那么数组应该是这样的:
Array
(
[0] => TTT 1000 S/Certificate/English
[1] =>TTT 1000 S/Certificate/Spanish
[2] => TTT 1100 S/Certificate/English
[3] => TTT 1100 S/Certificate/Spanish
)
我写了代码,但它真的很乱而且很长而且不能正常工作。我确信这可以以某种方式简化,但我有足够的知识来解决这个问题。如果有人知道如何处理这种情况,请提供帮助。谢谢。
【问题讨论】:
-
如果是单值,你想要的输出是什么?您想在所有路径中添加该单个值吗?
-
这是个好问题,我在编辑后的代码中添加了答案。