ArrayUtils::multiInMultiarray()   A
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6.0061

Importance

Changes 0
Metric Value
cc 6
eloc 19
nc 6
nop 4
dl 0
loc 31
ccs 17
cts 18
cp 0.9444
crap 6.0061
rs 9.0111
c 0
b 0
f 0
1
<?php
2
3
namespace Cdf\BiCoreBundle\Utils\Arrays;
4
5
class ArrayUtils
6
{
7
    /**
8
     * La funzione cerca un valore $elem nell'array multidimensionale $array all'interno di ogni elemento con chiave $key di ogni riga di array
9
     * e restituisce l'indice.
10
     *
11
     * @param mixed $elem Elemento da cercare nell'array
12
     * @param array<mixed> $array Array nel quale cercare
13
     * @param string $key Nome della chiave nella quale cercare $elem
14
     *
15
     * @return mixed False se non trovato l'elemento, altrimenti l'indice in cui si è trovato il valore
16
     */
17 1
    public static function inMultiarray($elem, $array, $key)
18
    {
19 1
        foreach ($array as $indice => $value) {
20 1
            if (!is_array($value)) {
21
                return false;
22
            }
23 1
            if (array_key_exists($key, $value)) {
24 1
                foreach ($value as $nomecolonna => $colonna) {
25 1
                    if ($colonna === $elem && $nomecolonna == $key) {
26 1
                        return $indice;
27
                    }
28
                }
29
            } else {
30
                return false;
31
            }
32
        }
33
34 1
        return false;
35
    }
36
37
    /**
38
     * La funzione cerca un valore $elem nell'array multidimensionale $array all'interno di ogni elemento con chiave $key di ogni riga di array
39
     * e restituisce l'indice.
40
     *
41
     * @param mixed $elem Elemento da cercare nell'array
42
     * @param array<mixed> $array Array nel quale cercare
43
     * @param mixed $key Nome della chiave nella quale cercare $elem
44
     *
45
     * @return mixed False se non trovato l'elemento, altrimenti il vettore con tutti gli indici
46
     */
47 2
    public static function inMultiarrayTutti($elem, $array, $key)
48
    {
49 2
        $trovato = array();
50
51 2
        foreach ($array as $indice => $value) {
52 2
            if (!is_array($value)) {
53
                return false;
54
            }
55 2
            if (array_key_exists($key, $value)) {
56 2
                foreach ($value as $nomecolonna => $colonna) {
57 2
                    if ($colonna === $elem && $nomecolonna == $key) {
58 2
                        $trovato[] = $indice;
59
                    }
60
                }
61
            } else {
62
                return false;
63
            }
64
        }
65
66 2
        return count($trovato) > 0 ? $trovato : false;
67
    }
68
69
    /**
70
     * La funzione cerca un valore $elem nell'array multidimensionale $array all'interno di ogni elemento con chiave $key di ogni riga di array
71
     * e restituisce l'indice.
72
     *
73
     * @param array<mixed> $array Array nel quale cercare
74
     * @param array<mixed> $search Chiave-valore da cercare
75
     *
76
     * @return mixed False se non trovato l'elemento, altrimenti l'indice in cui si trova il valore
77
     */
78 1
    public static function multiInMultiarray($array, $search, bool $debug = false, bool $tutti = false)
0 ignored issues
show
Unused Code introduced by
The parameter $debug is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

78
    public static function multiInMultiarray($array, $search, /** @scrutinizer ignore-unused */ bool $debug = false, bool $tutti = false)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
79
    {
80 1
        $primo = true;
81 1
        $vettorerisultati = array();
82
83 1
        foreach ($search as $key => $singolaricerca) {
84 1
            $trovato = self::inMultiarrayTutti($singolaricerca, $array, $key);
85
86 1
            if (false === $trovato) {
87 1
                $vettorerisultati = false;
88 1
                break;
89
            }
90
91 1
            if ($primo) {
92 1
                $vettorerisultati = $trovato;
93
            } else {
94
                $vettorerisultati = array_intersect($vettorerisultati, $trovato);
95
            }
96
97 1
            $primo = false;
98
        }
99
100 1
        if (false === $vettorerisultati) {
101 1
            $risposta = false;
102 1
        } elseif (false === $tutti) {
103 1
            $risposta = reset($vettorerisultati);
104
        } else {
105 1
            $risposta = $vettorerisultati;
106
        }
107
108 1
        return $risposta;
109
    }
110
111
    /**
112
     * La funzione ordina un array multidimensionale $array.
113
     *
114
     * param array<mixed> $array Array da ordinare
115
     * param string $key Nome della chiave dell'array per cui ordinare
116
     * param int $type Tipo di ordinamento SORT_ASC, SORT_DESC
117
     *
118
     * @return array<mixed> Ritorna l'array ordinato
119
     *
120
     * @example arrayOrderby($rubrica,"cognome",SORT_ASC);
121
     *          <br/>$rubrica = array();<br/>
122
     *          $rubrica[] = array("matricola" => 99999, "cognome" => "rossi", "nome" => "mario");<br/>
123
     *          $rubrica[] = array("matricola" => 99998, "cognome" => "bianchi", "nome" => "andrea");
124
     *          $rubrica[] = array("matricola" => 99997, "cognome" => "verdi", "nome" => "michele");
125
     *          rusulterà<br/>$rubrica[0]("matricola"=>99998,"cognome"=>"bianchi","nome"=>"andrea")
126
     *          $rubrica[1]("matricola"=>99999,"cognome"=>"rossi","nome"=>"mario")
127
     *          $rubrica[2]("matricola"=>99997,"cognome"=>"verdi","nome"=>"michele")
128
     */
129 2
    public static function arrayOrderby()
130
    {
131 2
        $args = func_get_args();
132 2
        $data = array_shift($args);
133 2
        foreach ($args as $n => $field) {
134 2
            if (is_string($field)) {
135 2
                $tmp = array();
136 2
                foreach ($data as $key => $row) {
137 2
                    $tmp[$key] = $row[$field];
138
                }
139 2
                $args[$n] = $tmp;
140
            }
141
        }
142 2
        $args[] = &$data;
143 2
        call_user_func_array('array_multisort', $args);
144
145 2
        return array_pop($args);
146
    }
147
148
    /**
149
     *
150
     * @param mixed $needle
151
     * @param array<mixed> $haystack
152
     * @return mixed
153
     */
154
    public function arraySearchRecursive($needle, $haystack)
155
    {
156
        foreach ($haystack as $key => $val) {
157
            if (stripos(implode('', $val), $needle) > 0) {
158
                return $key;
159
            }
160
        }
161
162
        return false;
163
    }
164
165
    /**
166
     * La funzione ordina un array multidimensionale  che ha per indice chiavi associative.
167
     *
168
     * @param array<mixed> $array Array da ordinare passato per riferimento
169
     * @param string $subkey Nome della chiave dell'array associato alla chiave per cui ordinare
170
     * @param bool $sort_ascending Tipo di ordinamento true ASC, false DESC
171
     *
172
     * @example sortMultiAssociativeArray($rubrica, "ordine", true);<code>
173
     *          array["nominativo" => ["nomecampo" => "nominativo","ordine" => 30],<br/><br/>
174
     *          "datanascita" => ["nomecampo" => "datanascita","ordine" => 10],<br/><br/>
175
     *          "telefono" => ["nomecampo" => "telefono","ordine" => 20]<br/><br/>
176
     *          ritorna:<br/><br/>
177
     *          array["datanascita" => ["nomecampo" => "datanascita","ordine" => 10],<br/><br/>
178
     *          "telefono" => ["nomecampo" => "telefono","ordine" => 20],<br/><br/>
179
     *          "nominativo" => ["nomecampo" => "nominativo","ordine" => 30]</code>
180
     *
181
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
182
     */
183 13
    public static function sortMultiAssociativeArray(&$array, $subkey, $sort_ascending = true) : void
184
    {
185 13
        $temp_array = array();
186
        //Se sono tutti uguali (stesso "peso") evita di fare l'ordinamento
187 13
        if (!self::isSortArray($array, $subkey)) {
188 13
            if (count($array)) {
189 13
                $temp_array[key($array)] = array_shift($array);
190
            }
191
192 13
            foreach ($array as $key => $val) {
193 13
                $offset = 0;
194 13
                $found = false;
195 13
                foreach ($temp_array as $tmp_key => $tmp_val) {
196 13
                    if (!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey])) {
197 13
                        $temp_array = array_merge(
198 13
                            (array) array_slice($temp_array, 0, $offset),
199 13
                            array($key => $val),
200 13
                            array_slice($temp_array, $offset)
201 13
                        );
202 13
                        $found = true;
203
                    }
204 13
                    ++$offset;
205
                }
206 13
                if (!$found) {
207 4
                    $temp_array = array_merge($temp_array, array($key => $val));
208
                }
209
            }
210 13
            $array = self::executeSortMultiAssociativeArray($temp_array, $sort_ascending);
211
        }
212
    }
213
214
    /**
215
     *
216
     * @param array<mixed> $array
217
     * @param string $subkey
218
     * @return bool
219
     */
220 13
    private static function isSortArray($array, $subkey) : bool
221
    {
222 13
        $check = null;
223 13
        $diff = false;
224 13
        $key = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $key is dead and can be removed.
Loading history...
225
        //Controlla se sono tutti uguali i valori per i quali deve fare l'ordinamento
226 13
        foreach ($array as $key => $val) {
227 13
            if (isset($check) && $check != $val[$subkey]) {
228 13
                $diff = true;
229 13
                break;
230
            } else {
231 13
                $check = $val[$subkey];
232
            }
233
        }
234
235 13
        return !$diff;
236
    }
237
238
    /**
239
     *
240
     * @param array<mixed> $temp_array
241
     * @param bool $sort_ascending
242
     * @return array<mixed>
243
     */
244 13
    private static function executeSortMultiAssociativeArray($temp_array, $sort_ascending) : array
245
    {
246 13
        if ($sort_ascending) {
247 13
            $array = array_reverse($temp_array);
248
        } else {
249 1
            $array = $temp_array;
250
        }
251
252 13
        return $array;
253
    }
254
}
255