使用相同的键将递归数组更改为单个数组

时间:2015-08-13 13:26:21

标签: php mysql arrays json

我想知道是否可以更改数组结构,目前我正在接收这个数组:

[{"ano":["2004","2006"]},{"ano":["2006",""]},{"ano":["2011",""]},{"ano":["2013",""]}]

我需要将这些日期逐行拆分:

[{"ano":"2004"},{"ano":"2006"},{"ano":"2006"},{"ano":"2011"}]

所以,基本上我认为我可以清理空值和重复值,然后拆分数组或什么?

我正在使用PHP和MySQL SELECT来返回这样的值:

while($ano = $pegaAno->fetchObject()){
    $ar1 = array("ano" => $ano->inicio);
    $ar2 = array("ano" => $ano->fim);
    $result = array_merge_recursive($ar1, $ar2);
    //print_r($result);
    array_push($return_arr,$result);
}

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

您也可以尝试使用此代码

    $input[0]['anno'] = array("2004","2006");
    $input[1]['anno'] = array("2008","");
    $input[2]['anno'] = array("2002","2006");
    $input[3]['anno'] = array("2004","2013");
    $arr = array();   
    foreach ($input as $value) { 
    foreach ($value as $key =>  $value1) { 
        foreach ($value1 as  $value2) { 
            $arr[] = $value2;
        }   
    } 

    } 
    $resulted = array_filter(array_unique($arr));
    $resulted_array = array();
    foreach ($resulted as $value) { 
        $resulted_array[][$mainkey] = $value;
    }
    print_r($resulted_array);

//RESULT 

Array
(
    [0] => Array
        (
            [anno] => 2004
        )

    [1] => Array
        (
            [anno] => 2006
        )

    [2] => Array
        (
            [anno] => 2008
        )

    [3] => Array
        (
            [anno] => 2002
        )

    [4] => Array
        (
            [anno] => 2013
        )

)