doujizhong8352 2018-06-01 08:38
浏览 61
已采纳

PHP 5.6展平具有多个字段的多维数组

I have a multidimensional array that looks like this:

array (size=2)
  0 => 
    array (size=3)
      'a1' => boolean true
      'b1' => string 'abc' (length=6)
      'c1' => string 'def' (length=8)
  1 => 
    array (size=5)
      'a2' => boolean true
      'b2' => string 'fgh' (length=6)
      'c2' => string 'ijk' (length=8)
      'd2' => string 'lmn' (length=4)
      'e2' => string 'opq' (length=4)

And my goal is to get this:

array (size=8)
  'a1' => boolean true
  'b1' => string 'abc' (length=6)
  'c1' => string 'def' (length=8)
  'a2' => boolean true
  'b2' => string 'fgh' (length=6)
  'c2' => string 'ijk' (length=8)
  'd2' => string 'lmn' (length=4)
  'e2' => string 'opq' (length=4)

I've tried something with the array_map function but I don't know how to get all fields:

$params = array_map(function($element) {
    return $element['a1'];
}, $params);
  • 写回答

8条回答 默认 最新

  • dongxianji0968 2018-06-01 08:41
    关注

    Try to use this :

    function array_flatten($array) {
        if (!is_array($array)) {
            return FALSE;
        }
        $result = array();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $result = array_merge($result, array_flatten($value));
            }
            else {
                $result[$key] = $value;
            }
        }
        return $result;
    }
    

    I test it with :

    $array = array(
        0 => array(
            'a1' => true,
            'b1' => 'abc',
            'c1' => 'def',
        ),
        1 => array(
            'a2' => true,
            'b2' => 'fgh',
            'c2' => 'ijk',
            'd2' => 'lmn',
            'e2' => 'opq'
        )
    );
    
    $result = array_flatten($array);
    
    var_dump($result);
    

    The output is :

    array (size=8)
        'a1' => boolean true
        'b1' => string 'abc' (length=3)
        'c1' => string 'def' (length=3)
        'a2' => boolean true
        'b2' => string 'fgh' (length=3)
        'c2' => string 'ijk' (length=3)
        'd2' => string 'lmn' (length=3)
        'e2' => string 'opq' (length=3)
    

    But I prefer to be honnest, I think it's a function I got from a duplicate question, can't find it again ! But I used it to "flatten" some array and it works well :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化