首頁 > 後端開發 > php教程 > 关于合并二维数组的问题

关于合并二维数组的问题

WBOY
發布: 2016-06-23 13:48:39
原創
770 人瀏覽過

有一个数组:
Array
(
    [0] => Array
        (
            [a] => Array
                (
                    [id] => 4
                )

        )

    [1] => Array
        (
            [a] => Array
                (
                    [id] => 5
                )

        )

    [2] => Array
        (
            [b] => Array
                (
                    [id] => 4
                )

        )

    [3] => Array
        (
            [b] => Array
                (
                    [id] => 7
                )

        )

)

请问如何合并成
Array(
[0]=>4
[1]=>5
[2]=>4
[3]=>7
)

value都是二维数组id


回复讨论(解决方案)

$arr = Array(    '0' => Array        (            'a' => Array                (                    'id' => 4                )        ),    '1' => Array        (            'a' => Array                (                    'id' => 5                )        ),    '2' => Array        (            'b' => Array                (                    'id' => 4                )        ),    '3' => Array        (            'b' => Array                (                    'id' => 7                )        ));$new_arr = array();foreach($arr as $vl){    foreach($vl as $v) $new_arr[] = $v['id'];}print_r($new_arr);
登入後複製

$a = array (  0 =>   array (    'a' =>     array (      'id' => '4',    ),  ),  1 =>   array (    'a' =>     array (      'id' => '5',    ),  ),  2 =>   array (    'b' =>     array (      'id' => '4',    ),  ),  3 =>   array (    'b' =>     array (      'id' => '7',    ),  ),);foreach($a as $t) $b[] = current(current($t));print_r($b);
登入後複製
Array(    [0] => 4    [1] => 5    [2] => 4    [3] => 7)
登入後複製
登入後複製

$a = array (  0 =>   array (    'a' =>     array (      'id' => '4',    ),  ),  1 =>   array (    'a' =>     array (      'id' => '5',    ),  ),  2 =>   array (    'b' =>     array (      'id' => '4',    ),  ),  3 =>   array (    'b' =>     array (      'id' => '7',    ),  ),);$num=sizeof($a);array_walk_recursive($a,'my',$num);function my($v,$k,$num){    static $arr=array();    $arr[]=$v;    if(sizeof($arr)==$num){        print_r($arr);    }}
登入後複製


Array(    [0] => 4    [1] => 5    [2] => 4    [3] => 7)
登入後複製
登入後複製

用闭包就这么写

$a = array (  0 =>   array (    'a' =>     array (      'id' => '4',    ),  ),  1 =>   array (    'a' =>     array (      'id' => '5',    ),  ),  2 =>   array (    'b' =>     array (      'id' => '4',    ),  ),  3 =>   array (    'b' =>     array (      'id' => '7',    ),  ),);array_walk_recursive($a, function($v) use (&$b) { $b[] = $v; });print_r($b);
登入後複製

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板