If I understand correctly the goal is to transfer from the input array all elements that have the same prefix characterized by an expression followed by a underscore.
Therefore, I propose the scheme below:
$filtered = array();
array_walk(
$arr,
function( $current, $offset ) use( $arr, &$filtered ) {
preg_match( '/(\w+_\d+)/', $offset, $matches );
if( count( $matches ) > 0 && array_key_exists( $matches[ 1 ], $arr ) ) {
$filtered[ $matches[ 1 ] ] = $current;
}
}
);
Using the input array with the same name as today ($arr) the resulting matrix $Filtered will have the following values:
array(
'numero_1' => '1',
'rua_1' => 'rua 1',
'numero_2' => '2',
'rua_2' => 'rua 2'
)
Your second question can be answered simply by computing the difference between the two original and filtered arrays:
$diff = array_diff_assoc( $arr, $filtered );
The matrix $diff has the following values:
array(
'id' => '147',
'nome' => 'João',
'email' => '[email protected]',
'data_nascimento' => '05/01/1987',
'submit' => 'Salvar'
)
This approach has the advantages:
- Do not depend on a fixed expression, that is, as long as all similarities follow the same format prefix, it will work in the whole matrix.
- It is fast, because it needs calculations, complex conditions and nested loops. So even though large array is bad enough for your Application, this procedure won’t be your bottleneck.
But what’s the common denominator?
numero_1
andnumero_2
are two different things. Or do you intendnumero_X
?– Zuul
What do you mean, "having the names of positions in common"? If you’re talking about the name of the key - what comes before the
=>
- no two keys with the same name will exist in an array.– Thomas
Why "rua_1" and "rua_2" did not follow the same criteria?
– Bacco
It did not follow the same pattern because I will take this array and do the foreach in both street and number, that is where there will be street number
– Wallace Ferreira