【问题标题】:Match and split of an Array of String PHP字符串数组的匹配和拆分 PHP
【发布时间】:2011-08-03 18:40:30
【问题描述】:

我在查找代码时遇到了麻烦:

我有这个数组:

$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,但我无法处理这个

【问题讨论】:

  • 你是从别人那里得到这个数组还是你自己定义的?如果是后者,为什么不使用二维数组?
  • 我从表单中得到这个数组
  • @grteibo:表单可以向您发送数组。 <input name="formacion_c[]" />。那么$_POST['formacion_c'] 将是一个数组。
  • 是的,但这在 Zend_Form_Elements 中是不可能的,谢谢

标签: php arrays split match


【解决方案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";
    }
}

演示:http://ideone.com/iscQ7

【讨论】:

  • 这段代码没问题!只是“c_formacion_”而不是“formacion_c_”谢谢!
【解决方案2】:

为什么不为此使用多维数组?

代替:

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

[编辑] 我注意到您在 cmets 中说您从表单中获取此数组。您可以在 HTML 表单中拥有多维数组。 [/编辑]

如果您无法更改代码,我猜您可以遍历每个元素并比较键:

$keyStart = 'formacion_c_';
foreach($filtros as $key => $value) {
     if(strstr($key, $keyStart)) {
          $id = str_replace($keyStart, '', $key);
     }
}

【讨论】:

  • 嗯我想我不能在 Zend_forms_elements 中做多维数组,我从不同的 Zend_Form_Element_Select 得到这个 Formacion_c_1,formacion_c_2
猜你喜欢
  • 1970-01-01
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-08
  • 2016-12-31
相关资源
最近更新 更多