我有一个三维数组。我想右边的函数将它转换为单维数组并保留前一个子键。我该怎么做?
array(2) {
[0]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(1) "4"
["assignedlessons"]=>
string(2) "69"
}
[1]=>
array(2) {
["id"]=>
string(1) "4"
["assignedlessons"]=>
string(3) "308"
}
}
array(2) {
[0]=>
array(2) {
["id"]=>
string(1) "10"
["assignedlessons"]=>
string(2) "50"
}
[1]=>
array(2) {
["id"]=>
string(1) "10"
["assignedlessons"]=>
string(2) "91"
}
}
}
我想把它转换成像这样的结构:
array(0) {
["id"]=>
string(1) "4"
["assignedlessons"]=>
string(2) "69"
}
array(1) {
["id"]=>
string(1) "4"
["assignedlessons"]=>
string(3) "308"
}
array(2) {
["id"]=>
string(1) "10"
["assignedlessons"]=>
string(2) "50"
}
array(3) {
["id"]=>
string(1) "10"
["assignedlessons"]=>
string(2) "91"
}
我有这个功能:
function toSingleDimentionalArray($array){
$final = array();
foreach($array as $value){
foreach($array as $key => $val){
$final[]['id'] = $val['id'];
$final[]['assignedlessons'] = $val['assignedlessons'];
}
}
return $final;
}
但它只返回这样的东西:
array(19648) {
[0]=>
array(1) {
["id"]=>
string(1) "4"
}
[1]=>
array(1) {
["assignedlessons"]=>
string(2) "69"
}
[2]=>
array(1) {
["id"]=>
string(1) "4"
}
[3]=>
array(1) {
["assignedlessons"]=>
string(3) "308"
}
答案 0 :(得分:2)
这将有效
function toNotActuallyASingleDimensionalArray($array) {
$final = array();
foreach($array as $subarray) {
foreach($subarray as $val) {
$final[] = $val;
}
}
return $final;
}
答案 1 :(得分:1)
$final_array = array();
foreach($array as $sub_array)
{
foreach($sub_array as $temp_array)
{
$final_array[] = $temp_array;
}
}
答案 2 :(得分:0)
function simplify_array($array, $first_level=true) {
foreach($array as $key => $value) {
$last_level = !is_array($value);
if($last_level) {
return $array;
}else if($first_level) {
$return[] = simplify_array($value, false);
}else{
return simplify_array($value, false);
}
}
return $return;
}
print_r(simplify_array($arr));
HTH
它适用于n维数组