2d multidimensional array to 1d array in php

后端 未结 8 1731
陌清茗
陌清茗 2021-01-06 00:51

Just wondering if anyone has transformed a 2 dim array to a one dim array in php. I\'ve yet to come across a clear explanation in php. Any suggestion would be appreciated.

8条回答
  •  走了就别回头了
    2021-01-06 01:33

    Your first thought should be array_reduce() whenever you have lots of something in an array and you just want one something by itself which represents them all in some way.

    From the PHP docs:

    array_reduce — Iteratively reduce the array to a single value using a callback function

    In the case of 2D => 1D array conversion, the something is array; we have lots of them in an array but we just want one of them by itself.

    function array2dTo1d($array2d)
    {
        return array_reduce($array2d, function($carry, $array) {
            return array_merge($carry, $array);
        }, []);
    }
    
    var_dump(array2dTo1d(
        [
            [23423, 5454, 567],
            [4565, 687],
        ]
    ));
    
    

    Result:

    array(5) {
      [0] =>
      int(23423)
      [1] =>
      int(5454)
      [2] =>
      int(567)
      [3] =>
      int(4565)
      [4] =>
      int(687)
    }
    

提交回复
热议问题