main.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
$arr = [
  'owner' => [
    'table' => 'owner',
    'cols' => [
      'name' => 'Name',
      'address' => [
        'table' => 'Address',
        'cols' => [
          'line1' => 'Street Line 1',
          'line2' => 'Street Line 2',
          'city' => 'City',
          'state' => [
            'table' => 'State',
            'cols' => [
              'stateName' => 'State'
            ] 
          ],
          'postal_code' => 'Postal Code',
        ]
      ]
    ]
  ],
  'renter' => [
    'table' => 'renter',
    'cols' => [
      'name' => 'Name',
      'address' => [
        'table' => 'Address',
        'cols' => [
          'line1' => 'Street Line 1',
          'line2' => 'Street Line 2',
          'city' => 'City',
          'state' => [
            'table' => 'State',
            'cols' => [
              'stateName' => 'State'
            ] 
          ],
          'postal_code' => 'Postal Code',
        ]
      ]
    ]
  ]
];

/*
[
  [
    'key' => 'owner.name',
    'label' => 'Name'
  ],
  [
    'key' => 'owner.address.line1',
    'label' => 'Street Line 1'
  ],
  [
    'key' => 'owner.address.line2',
    'label' => 'Street Line 2'
  ],
  [
    'key' => 'owner.address.city',
    'label' => 'City'
  ],
  [
    'key' => 'owner.address.state.stateName',
    'label' => 'State'
  ],
  [
    'key' => 'owner.address.postal_code',
    'label' => 'Postal Code'
  ],
]
*/

function f(array $a, array $n = []) {
  if (isset($a['cols'])) { return f($a['cols'], $n); }

  $results = [];
  foreach ($a as $k => $v) {
    if (is_array($v)) {
      $results = array_merge($results, f($v['cols'], array_merge($n, [$k])));
      continue;
    }

    $results[] = ['key' => implode('.', $n) . '.' . $k, 'label' => $v];
  }

  return $results;
}

print_r(f($arr));

function flatten(array $a, string $path = '') {
    if (isset($a['cols'])) {
        return flatten($a['cols'], $path);
    }
    
    $pairs = [];
    foreach ($a as $k => $v) {
        $p = empty($path) ? $k : "{$path}.{$k}";
        if (is_array($v)) {
            array_push($pairs, ...flatten($v, $p));
        } else {
            $pairs[] = ["key" => $p, "label" => $v];
        }
    }
    return $pairs;
}

// print_r(flatten(['owner' => $arr['owner']]));
?>
PHP 7.0.8 (cli) (built: Jun 23 2016 23:39:14) ( NTS ) Copyright (c) 1997-2016 The PHP Group Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies