如何在不使用键名的情况下重新排列php数组

时间:2017-06-29 11:31:08

标签: php arrays

我的数组在下面我需要安排像array2(不使用$ aa ['caption1']直接名称) arrray1

Array
(
    [0] => Array
        (
            [caption1] => Array
                (
                    [0] => gfdhgfjhg
                    [1] => dfhfgjghk
                )

            [caption2] => Array
                (
                    [0] => shgjgh
                    [1] => dhfgkgjl
                )

            [banner_image] => Array
                (
                    [0] => assets/images/page_content/img_namT7.jpg
                    [1] => assets/images/page_content/img_R8mzP.jpg
                )

        )

    [1] => Array
        (
            [heading] => Array
                (
                    [0] => 
                )

            [pragraph] => Array
                (
                    [0] => 
                )

        )
)

arrray2是(必填格式)

Array
(
    [0] => Array
        (
          array('caption1'=>'caption1','caption2'=>'shgjgh','banner_image'=>'assets/images/page_content/img_namT7.jpg'),
          array('caption1'=>'dfhfgjghk','caption2'=>'dhfgkgjl','banner_image'=>'page_content/img_R8mzP.jpg')           
        )

    [1] => Array
        (
           array('heading'=>'','pragraph'=>''),
           array('heading'=>'fgh','pragraph'=>'ghgh'),
        )
)

请任何人帮助我。

1 个答案:

答案 0 :(得分:1)

使用array_keysarray_maparray_combine函数的解决方案:

// $arr is your initial array
$result = [];
foreach($arr as $v){
    $keys = array_keys($v);
    $data = call_user_func_array('array_map', [null] + $v);
    $result[] = array_map(function($item) use($keys){ 
        return array_combine($keys, $item); 
    }, $data);
}

print_r($result);

输出:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [caption1] => gfdhgfjhg
                    [caption2] => shgjgh
                    [banner_image] => assets/images/page_content/img_namT7.jpg
                )

            [1] => Array
                (
                    [caption1] => dfhfgjghk
                    [caption2] => dhfgkgjl
                    [banner_image] => assets/images/page_content/img_R8mzP.jpg
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [heading] => 
                    [pragraph] => 
                )
        )
)