我有一个以下格式的多维数组。我尝试做什么我得到未定义的偏移误差或重复的数组单元格。
arr[] = Array
(
[0] => Array
(
[grp1] = A
[grp2]=Array(
[0] => a
[1] => b
[2] => c
)
)
[1] => Array
(
[grp1] = B
[grp2]=Array(
[0] => d
[1] => e
)
)
)
我想将上面的数组转换为以下格式。
arr[] = Array
(
[0] => Array
(
[grp1] = A
[grp2]=a
)
[1] => Array
(
[grp1] = A
[grp2]=b
)
[2] => Array
(
[grp1] = A
[grp2]=c
)
[3] => Array
(
[grp1] = B
[grp2]=d
)
[4] => Array
(
[grp1] = B
[grp2]=e
)
)
首先抱歉我的问题没有得到很好的解释。实际上我不知道在这种情况下要问什么。任何修改都将受到赞赏。
答案 0 :(得分:3)
我通常不会对这样简单的事情给出完整的答案,但此刻我没有太多其他事情要做。我没有在散文中解释代码,而是对所有陈述进行了评论:
// Create a new array to hold the modified values
$newArr = array();
// Go over each item
foreach ($arr as $item) {
// Grab the uppercase letter
$uppercaseLetter = $item['grp1'];
// Go over the lowercase letters
foreach ($item['grp2'] as $lowercaseLetter) {
// Combine the uppercase and lowercase letters
// into a new array
$newArr[] = array(
'grp1' => $uppercaseLetter,
'grp2' => $lowercaseLetter,
);
}
}
// Show the new array
var_dump($newArr);
答案 1 :(得分:1)
$array = array();
foreach($arr as $v){
foreach($v['grp2'] as $val){
$array[] = array('grp1' => $v['grp1'], 'grp2' => $val);
}
}
print_r($array);
答案 2 :(得分:0)
<?php
$temp = array();
$i= 0;
foreach($arr as $key=>$value){
foreach($value["grp2"] as $key2=>$value2){
$temp[$i]["grp1"] = $value["grp1"];
$temp[$i]["grp2"] = $value2;
++$i;
}
}
print_r ($temp);
?>
结果:
Array (
[0] => Array ( [grp1] => A [grp2] => a )
[1] => Array ( [grp1] => A [grp2] => b )
[2] => Array ( [grp1] => A [grp2] => c )
[3] => Array ( [grp1] => B [grp2] => d )
[4] => Array ( [grp1] => B [grp2] => e ) )