Match and split of an Array of String PHP
I'm having troubles finding the code for this:
I have this array:
$filtros['code'] = 1
$filtros['name'] = 'John'
$filtros['formacion_c_1'] = 2
$filtros['formacion_c_2'] = 1
$filtros['formacion_c_3'] = 2
And I need to catch the number of each "formacion_c_{number}" and his value
echo "The Formation number {number} has the value $filtros[formacion_c_{number}]";
the result that I need is something like :
The Formation number 1 has the value 2.
The Formation number 2 has the value 1.
The Formation number 3 has the value 2.
surely the solution i开发者_如何转开发s with some preg_split or preg_match, but I can't handle this
foreach($filtros as $key=>$val){
if(preg_match('/^formacion_c_(\d)+$/', $key, $match) === 1){
echo "The Formation number {$match[1]} has the value $val";
}
}
Demo: http://ideone.com/iscQ7
Why don't you use multidimensional arrays for this?
Instead of:
filtros['formacion_c_1'] = 2
filtros['formacion_c_2'] = 1
filtros['formacion_c_3'] = 2
Why not:
filtros['formacion_c']['1'] = 2
filtros['formacion_c']['2'] = 1
filtros['formacion_c']['3'] = 2
[edit] I noticed in the comments you said you get this array from a form. You can have multidimensional arrays in HTML forms. [/edit]
If you can't change the code I guess you could loop through each element and compare the key:
$keyStart = 'formacion_c_';
foreach($filtros as $key => $value) {
if(strstr($key, $keyStart)) {
$id = str_replace($keyStart, '', $key);
}
}
精彩评论