很抱歉这个标题非常糟糕,我不是母语人士,也不确定如何用这句话来表达。
这是我的问题:
我有一个非常长的数组格式:
$array = array(
'key1.value1' => '1',
'key1.value2' => '0',
'key1.value3' => '1',
'key2.value1' => '0',
'key2.value2' => '0',
'key3.value1' => '1'
);
从这个数组中,我想换一个这种格式:
$newArray = array(
'key1' => array(
'value1' => '1',
'value2' => '0',
'value3' => '1'
),
'key2' => array(
'value1' => '0',
'value2' => '0'
),
'key3' => array(
'value1' => '1'
)
);
我尝试了一些方法,但实际上并没有找到任何不长的解决方案,所以我想知道是否有任何提示/技巧可以轻松完成!
非常感谢!
答案 0 :(得分:1)
$array = array(
'key1.value1' => '1',
'key1.value2' => '0',
'key1.value3' => '1',
'key2.value1' => '0',
'key2.value2' => '0',
'key3.value1' => '1'
);
$Results = array();
foreach($array as $key=>$value){
$KeyValue = explode(".",$key);
if(!isset($Results[$KeyValue[0]])){
$Results[$KeyValue[0]] = array();
}
$Results[$KeyValue[0]][end($KeyValue)] = $value;
}
print_r($Results);
答案 1 :(得分:0)
试试这个:
$generate = [];
foreach($array as $key=>$val ){
list($first, $second) = split('.', $key);
if(!isset($genrate[$first]){
$genrate[$first] = [];
if(!$genrate[$first][$second]){
$genrate[$first][$second]= [];
}
}
$genrate[$first][$second] = $val;
}
期待它有所帮助。 TKS
答案 2 :(得分:0)
使用explode()
函数的简短解决方案:
$transformed = [];
foreach ($array as $k => $v) {
$pair = explode('.', $k);
$transformed[$pair[0]][$pair[1]] = $v;
}
print_r($transformed);
输出:
Array
(
[key1] => Array
(
[value1] => 1
[value2] => 0
[value3] => 1
)
[key2] => Array
(
[value1] => 0
[value2] => 0
)
[key3] => Array
(
[value1] => 1
)
)