我遇到麻烦找到这个代码:
我有这个数组:
$filtros['code'] = 1
$filtros['name'] = 'John'
$filtros['formacion_c_1'] = 2
$filtros['formacion_c_2'] = 1
$filtros['formacion_c_3'] = 2
我需要记下每个“formacion_c_ {number}”的数量和他的价值
echo "The Formation number {number} has the value $filtros[formacion_c_{number}]";
我需要的结果是:
The Formation number 1 has the value 2.
The Formation number 2 has the value 1.
The Formation number 3 has the value 2.
肯定解决方案是使用一些preg_split或preg_match,但我无法处理这个
答案 0 :(得分:1)
foreach($filtros as $key=>$val){
if(preg_match('/^formacion_c_(\d)+$/', $key, $match) === 1){
echo "The Formation number {$match[1]} has the value $val";
}
}
答案 1 :(得分:0)
为什么不为此使用多维数组?
而不是:
filtros['formacion_c_1'] = 2
filtros['formacion_c_2'] = 1
filtros['formacion_c_3'] = 2
为什么不:
filtros['formacion_c']['1'] = 2
filtros['formacion_c']['2'] = 1
filtros['formacion_c']['3'] = 2
[编辑] 我在评论中注意到你说你从表格中得到了这个数组。您可以在HTML表单中使用多维数组。 [/编辑]
如果您无法更改代码,我猜您可以遍历每个元素并比较密钥:
$keyStart = 'formacion_c_';
foreach($filtros as $key => $value) {
if(strstr($key, $keyStart)) {
$id = str_replace($keyStart, '', $key);
}
}