PHP 字符串数组的匹配和分割

发布于 2024-11-27 18:41:27 字数 573 浏览 2 评论 0原文

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

我有这个数组:

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

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 is with some preg_split or preg_match, but I can't handle this

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撑一把青伞 2024-12-04 18:41:27
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

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

山川志 2024-12-04 18:41:27

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

而不是:

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 表单中使用多维数组。
[/edit]

如果您无法更改代码,我想您可以循环遍历每个元素并比较密钥:

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

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);
     }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文