我需要分解一个数组的键值,并构建一个具有分解结果的新数组。下面的代码可用于一个子数组,我想我缺少一个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
)
$new_array=[];
foreach($array as $category => $tmp ){
foreach($tmp as $key => $value){
$exp = explode('_', $key);
$exp[] = $value;
$new_array[ $category ][] = $exp;
}
}