在PHP中获取多维数组的索引名称

时间:2017-04-23 01:34:33

标签: php arrays regex wordpress indexing

我有一个包含多个输入字段的表单,这些字段被序列化并通过AJAX传递给函数。在函数内部,我有以下形式的数据。我需要将Book-Keeperpublish-companies1作为单独的变量。

// $key = '_data'
// $values = {"name":"_data[Book-Keeper][publish_companies]","value":"1"}

这是功能代码。

function fnc_edit_roles(WP_REST_Request $request) {

    $variables = $_REQUEST; 

    // Get all $_POST variables into $data[] array with key=>value
    if( $variables ) {

        while ( list( $field, $value ) = each( $_REQUEST )) {

            if( $field !== '_nonce' ) {
                $data[$field] = $value;
            }

        } // end while

    } // end if

    foreach( $data as $key=>$values ) {
        // $key = '_data'
        // $values = {"name":"_data[Book-Keeper][publish_companies]","value":"1"}
        // How do I get 'Book-Keeper', 'publish_companies', and '1' into separate variables?

    }

    $result = array( 'msg' => $data, 'error' => false );
    return json_encode( $result );

}

这就是我如何获得HTML中的输入。

<form id="_user_roles_form" method="post" class="form-horizontal">
    <div class="form-group row">
        <label class="col-lg-6 control-label">Publish Companies</label>
        <div class="col-lg-6">
            <div class="btn-group" data-toggle="buttons">
                <label class="btn btn-default active">
                    <input type="radio" name="_data[Book-Keeper][publish_companies]" value="1"/> True
                </label>
                <label class="btn btn-default ">
                    <input type="radio" name="_data[Book-Keeper][publish_companies]" value="0"/> False
                </label>
            </div>
        </div>
    </div>
</form>

以下是我将输入数据传递给AJAX函数的方法。

var _data = jQuery('#_user_roles_form').serializeArray();

jQuery.ajax({
    url: myAjaxUrl,
    type: 'POST',
    data: _data,
    success: function( json ) {
        var result = JSON.parse( json );
        console.log( result.msg );
    }
});

长问题简介,如何从字符串Book-Keeper中获取publish_companies_data[Book-Keeper][publish_companies]keyarray_keys在此无效...

1 个答案:

答案 0 :(得分:0)

试试这个希望这会帮助你。我们在这里使用的是正则表达式:\[([\w\-]+)\],它将匹配示例:[something-some_value]

Try this code snippet here     

ini_set('display_errors', 1);

foreach ($data as $key => $values)
{
    //$key = '_data';
    //$values = '{"name":"_data[Book-Keeper][publish_companies]","value":"1"}';
    $array = json_decode($values, true);
    $value = $array["value"];//will contain value
    preg_match_all("/\[([\w\-]+)\]/", $array["name"], $matches);
    list($role_name,$cap_name)=$matches[1];
    echo $role_name;//will contain role name
    echo $cap_name;//will contain company name
}