PHP map()相当于将$ _POST变量解析为关联数组

时间:2016-09-29 07:26:44

标签: php arrays

我需要解析使用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

注意末尾的数字ID - 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完成此操作?

2 个答案:

答案 0 :(得分:2)

一个微不足道的regex solution(虽然这个正则表达式是quite expensive):

foreach ($_POST as $key => $value) {
    if (preg_match('/([^_]+)_([^_]+)$/', $key, $match)) {
        echo $my_arr[$match[2]][$match[1]];
    }
}

答案 1 :(得分:1)

您只需循环遍历数组并使用explode()函数。

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; 
}