PHP。二维数组转换为1维

时间:2014-01-31 13:39:52

标签: php arrays dimensional

我有一个名为$result_for_json_all

的数组
Array
(
[0] => Array
    (
    )

[1] => Array
    (
        [0] => Array
            (
                [CurrencyAbbreviation] => AUD
                [DateOfCurrencyRate] => 2012-12-11
                [NumberOfInputRow] => 1
                [FinalCurrencyRate] => 0.571
            )

    )

[2] => Array
    (
        [0] => Array
            (
                [CurrencyAbbreviation] => CAD
                [DateOfCurrencyRate] => 2013-12-22
                [NumberOfInputRow] => 4
                [FinalCurrencyRate] => 0.48
            )

        [1] => Array
            (
                [NumberOfInputRow] => 2
                [FinalCurrencyRate] => 
            )

        [2] => Array
            (
                [NumberOfInputRow] => 3
                [FinalCurrencyRate] => 
            )

    )

)

想要获得

Array
(
[0] => Array
            (
                [CurrencyAbbreviation] => AUD
                [DateOfCurrencyRate] => 2012-12-11
                [NumberOfInputRow] => 1
                [FinalCurrencyRate] => 0.571
            )

[1] => Array
            (
                [CurrencyAbbreviation] => CAD
                [DateOfCurrencyRate] => 2013-12-22
                [NumberOfInputRow] => 4
                [FinalCurrencyRate] => 0.48
            )

[2] => Array
            (
                [NumberOfInputRow] => 2
                [FinalCurrencyRate] => 
            )

[3] => Array
            (
                [NumberOfInputRow] => 3
                [FinalCurrencyRate] => 
            )


)

基于此https://stackoverflow.com/a/9416851/2118559创建的代码

function flatten($result_for_json_all) {
$arr = array();
foreach($result_for_json_all as $k => $v) {
    if(is_array($v)) {
        $arr = array_merge($arr, flatten($v, $k));
    }
    else{
        $arr[$k] = $v;
    }
}
return $arr;
}

echo '<pre>';
print_r(flatten($result_for_json_all));
echo 'result_for_json_all<pre>';

但是得到

 Array
 (
[CurrencyAbbreviation] => AUD
[DateOfCurrencyRate] => 2013-12-22
[NumberOfInputRow] => 3
[FinalCurrencyRate] => 
 )

请提出建议需要纠正的内容以获得必要的结果

2 个答案:

答案 0 :(得分:3)

<?php
    $result = array();

    foreach ($result_for_json_all as $outer_elt) {
        foreach ($outer_elt as $inner_elt) {
            $result[] = $inner_elt;
        }
    }

    var_dump($result);
?>

答案 1 :(得分:1)

嘿,尝试这样的事情:

<?php
// The original data
$org = Array(
  0 => Array(),
  1 => Array(
    0 => Array( "CurrencyAbbreviation" => "AUD" )
  ),
  2 => Array(
    0 => Array( "CurrencyAbbreviation" => "CAD", "DateOfCurrencyRate" => "2013-12-22"),
    1 => Array( "NumberOfInputRow" => 2 )
  )
);
print_r($org);

// The new array transformed
$arr = Array();
foreach ($org as $v1){
  foreach($v1 as $v2){
    $arr[] = $v2; 
  }
}
print_r($arr);
?>