在PHP中将三维数组转换为二维数组

时间:2016-11-02 18:53:40

标签: php arrays

这里需要一点帮助 我有这个数组:

0 => array:4 [▼
    "StudentName" => "John Doe "
    "StudentNumber" => "2055222"
    0 => array:1 [▼
      "Test" => 33.5
       ]
    1 => array:1 [▼
      "Assignment" => 57.0
       ]
 ]
1 => array:4 [▼
    "StudentName" => "Jane Doe"
    "StudentNumber" => "5222112"
    0 => array:1 [▼
       "Test" => 47.0
       ]
    1 => array:1 [▼
      "Assignment" => 68.0
   ]
]
2 => array:4 [▼
     "StudentName" => "Alice Doe"
     "StudentNumber" => "5555555"
     0 => array:1 [▼
         "Test" => 0.0
         ]
     1 => array:1 [▼
        "Assignment" => 67.0
    ]
]

我想把它转换成这样:

0 => array:4 [▼
"StudentName" => "John Doe "
"StudentNumber" => "20160022"
"Test" => 33.5
"Assignment" => 57.0]

我可以使用某种PHP功能吗? 编辑:添加了更多示例,以帮助您考虑更好的解决方案

3 个答案:

答案 0 :(得分:0)

PHP中没有原生数组变平,但你可以这样做:

function array_flatten($array) { 
    if (!is_array($array)) { 
        return false; 
    } 
    $result = array(); 
    foreach ($array as $key => $value) { 
        if (is_array($value)) { 
            $result = array_merge($result, array_flatten($value)); 
        } else { 
            $result[$key] = $value; 
        } 
    } 
    return $result; 
}

找到here

此处还有许多其他方法:How to Flatten a Multidimensional Array?

答案 1 :(得分:0)

你可以这样使用(未经测试):

$arr = Array();
foreach($oldArr AS $k => $v){
    if(is_array($v)){
        foreach($v AS $a => $b){
            $arr[$a] = $b;
        }
    }else{
        $arr[$k] = $v;
    }
}

答案 2 :(得分:0)

这应该有效:

// Store your new array in a separate variable to avoid key conflicts with trying to us unset() in a loop
$new_array = array();

foreach($original_array as $k=>$v)
{
    if(is_array($v)) // check if element is an array
    {
        foreach($v as $k2=>$v2) // loop the sub-array and add its keys/indexes to the new array
        {
            $new_array[$k2] = $v2;
        }
    }
    else
    {
        // the element is not a sub-array so just add the key and value to the new array
        $new_array[$k] = $v;
    }
}