【发布时间】:2020-05-28 06:54:01
【问题描述】:
我需要分解数组的键值并构建一个具有分解结果的新数组。下面的代码适用于一个子数组,我想我缺少一个 for 循环来处理数组值的迭代。
该解决方案还应处理“财务”子数组数据,以便在新数组中展开并显示。
我在后期会有 9 个子数组,因此需要分解数据并将结果移动到新数组中。
我的代码
<?php
$array = [
'company_info' => [
'country_period_0' => 10,
'currency_period_0' => 20
],
'finance' => [
'values_period_0' => 30
]
];
$newArray = [];
for ($i=0; $i <= 1 ; $i++) {
$array_1 = $array['company_info'];
$arrayKeys = array_keys($array_1);
$arrayValues = array_values($array_1);
$keySplits = explode("_", $arrayKeys[$i]);
for ($i=0; $i <= 2 ; $i++) {
$newArray[] = $keySplits[$i];
}
$newArray[3] = $arrayValues[0];
}
print_r($newArray);
结果
Array(
[0] => country
[1] => period
[2] => 0
[3] => 10
)
想要的结果
['company_info]
Array(
[0] => country
[1] => period
[2] => 0
[3] => 10
)
Array(
[0] => currency
[1] => period
[2] => 0
[3] => 20
)
['finance']
Array(
[0] => values
[1] => period
[2] => 0
[3] => 30
)
【问题讨论】:
-
您在外部和内部
for循环中保留了与迭代器相同的变量$i。在内部循环中,它在达到外部循环的最大值 ($i <= 1) 处增加$i。这不会修复您的整个代码,但这是一个好的开始
标签: php arrays multidimensional-array php-7.3