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

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 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥15 抖音看过的视频,缓存在哪个文件