我需要解析使用jQuery动态创建的$_POST表单变量。变量有一个共同的结构,即text_id。例如:
$_POST[ 'my_app_custom_size_23' ] = large
$_POST[ 'my_app_custom_color_23' ] = red
$_POST[ 'my_app_custom_style_23' ] = classic
$_POST[ 'my_app_custom_size_719' ] = medium
$_POST[ 'my_app_custom_color_719' ] = black
$_POST[ 'my_app_custom_style_719' ] = modern
$_POST[ 'my_app_custom_size_501' ] = large
$_POST[ 'my_app_custom_color_501' ] = white
$_POST[ 'my_app_custom_style_501' ] = classic
请注意末尾的数字标识- 23、719和501。它们需要作为关联数组中的键,例如:
$my_arr = array(
'23' => array(
'size' => 'large',
'color' => 'red',
'style' => 'classic'
),
'719' => array(
'size' => 'medium',
'color' => 'black',
'style' => 'modern'
),
'501' => array(
'size' => 'large',
'color' => 'white',
'style' => 'classic'
)
);
所以我可以引用类似的数据:
$size = $my_arr['719']['size']
每个var都以一个可预测的名称开始,以下划线和一个重要的数字id结束。
如何使用PHP完成?
一个简单的正则表达式解决方案(尽管这个正则表达式相当昂贵):
foreach ($_POST as $key => $value) {
if (preg_match('/([^_]+)_([^_]+)$/', $key, $match)) {
echo $my_arr[$match[2]][$match[1]];
}
}
您可以简单地遍历数组并使用explosion()函数。
foreach ($_POST as $k => $v) {
$keys = explode('_', $k); // Results in Array ( [0] => my [1] => app [2] => custom [3] => size [4] => 23 )
/* end($keys) would retrieve the last value i.e 23 for first one $keys[3] retrieves result like size, color etc. */
$result[end($keys)][$keys[3]] = $v;
}