1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* DronePHP (http://www.dronephp.com) |
4
|
|
|
* |
5
|
|
|
* @link http://github.com/Pleets/DronePHP |
6
|
|
|
* @copyright Copyright (c) 2016-2018 Pleets. (http://www.pleets.org) |
7
|
|
|
* @license http://www.dronephp.com/license |
8
|
|
|
* @author Darío Rivera <[email protected]> |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Drone\Util; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* ArrayDimension class |
15
|
|
|
* |
16
|
|
|
* Utils functions to operate arrays |
17
|
|
|
*/ |
18
|
|
|
class ArrayDimension |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* Converts a multidimensional array in a dimensional array |
22
|
|
|
* |
23
|
|
|
* @param array $array |
24
|
|
|
* @param string $glue |
25
|
|
|
* |
26
|
|
|
* @return array |
27
|
|
|
*/ |
28
|
3 |
|
public static function toUnidimensional(array $array, $glue) |
29
|
|
|
{ |
30
|
3 |
|
$new_config = []; |
31
|
3 |
|
$again = false; |
32
|
|
|
|
33
|
3 |
|
foreach ($array as $param => $configure) { |
34
|
3 |
|
if (is_array($configure)) { |
35
|
3 |
|
foreach ($configure as $key => $value) { |
36
|
3 |
|
$again = true; |
37
|
3 |
|
$new_config[$param . $glue . $key] = $value; |
38
|
|
|
} |
39
|
|
|
} else { |
40
|
3 |
|
$new_config[$param] = $configure; |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
3 |
|
return (!$again) ? $new_config : self::toUnidimensional($new_config, $glue); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Search inside a multi-dimensional array a value by nested keys |
49
|
|
|
* |
50
|
|
|
* Default value will be returned if any key in the haystack array does not exists |
51
|
|
|
* |
52
|
|
|
* @param array $needle |
53
|
|
|
* @param array $haystack |
54
|
|
|
* @param mixed $value |
55
|
|
|
* |
56
|
|
|
* @return mixed |
57
|
|
|
*/ |
58
|
|
|
public static function ifdef(array $needle, array $haystack, $value) |
59
|
|
|
{ |
60
|
|
|
$key = array_shift($needle); |
61
|
|
|
|
62
|
|
|
do { |
63
|
|
|
if (array_key_exists($key, $haystack)) { |
64
|
|
|
$haystack = $haystack[$key]; |
65
|
|
|
} else { |
66
|
|
|
return $value; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$key = count($needle) ? array_shift($needle) : null; |
70
|
|
|
|
71
|
|
|
if (is_null($key)) { |
72
|
|
|
return $haystack; |
73
|
|
|
} |
74
|
|
|
} while (!is_null($key)); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Transforms an object to an array |
79
|
|
|
* |
80
|
|
|
* @param mixed $obj |
81
|
|
|
* |
82
|
|
|
* @return array |
83
|
|
|
*/ |
84
|
3 |
|
public static function objectToArray($obj) |
85
|
|
|
{ |
86
|
3 |
|
if (is_object($obj)) { |
87
|
3 |
|
$obj = (array) $obj; |
88
|
|
|
} |
89
|
|
|
|
90
|
3 |
|
if (is_array($obj)) { |
91
|
3 |
|
$new = []; |
92
|
|
|
|
93
|
3 |
|
foreach ($obj as $key => $val) { |
94
|
3 |
|
$new[$key] = self::objectToArray($val); |
95
|
|
|
} |
96
|
|
|
} else { |
97
|
3 |
|
$new = $obj; |
98
|
|
|
} |
99
|
|
|
|
100
|
3 |
|
return $new; |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
|