如何使用PHP合并一个数组中的数组?

时间:2014-02-21 04:29:57

标签: php arrays

我有问题当我想要重建我的阵列。 这是我在phpfiddle.org上创建的

http://phpfiddle.org/main/code/tzp-t1u

任何人都可以给我建议吗?

1 个答案:

答案 0 :(得分:1)

此代码可以帮助您

<?php

$result = array (
        array(
                'lev1'=> null,
                'lev2'=> 34,
                'lev3'=> 21,
                'lev4'=> 22,
                'child' => 'cyaiooo'
        ),
        array(
                'lev1'=> null,
                'lev2'=> 34,
                'lev3'=> 10,
                'lev4'=> 8,
                'child' => 'test1'
        ),
        array(
                'lev1'=> null,
                'lev2'=> 34,
                'lev3'=> 21,
                'lev4'=> 22,
                'child' => 'hodem'
        )
);

$data = array();

foreach($result as $value)
{
    if(count($data)==0)
    {
        $data[] = $value;

    }else{

        foreach($data as &$container)
        {
            if($value['lev1']==$container['lev1']
                    &&
                $value['lev2']==$container['lev2']
                    &&
                $value['lev3']==$container['lev3']
                    &&
                $value['lev4']==$container['lev4'])
            {               

                if(is_string($container['child']))
                {
                    //get the string value
                    $string = $container['child'];

                    //unset the child string
                    unset($container['child']);

                    //declatre the array
                    $container['child'] = array();

                    $container['child'][] =  $string;
                }

                $container['child'][] =  $value['child'];

                break;

            }else{
                $data[] = $value;
                break;
            }
        }

    }
}

print_r($data);