首页 > 解决方案 > laravel 请求索引无法列出数组分类

问题描述

注意:我的问题不重复

我在站点外有表单并使用web api laravel 5.7,现在将这些参数作为帖子发送:

estate: "545345"
id_number: "43534545"
serial_number: "435435345"
type[code_id]: "45345345435"
type[company]: ""
type[country]: ""
type[maintenance_period]: ""
type[model]: "5435345435"
type[name]: "5345345345"
waranty[company_id]: "0"
waranty[duration]: ""
waranty[end]: ""
waranty[start]: ""

部分形式:

<input type="text" name="estate" required="">
<input type="text" name="id_number" required="">
<input type="text" name="type[code_id]">
<input type="text" name="type[company]">

现在我想获取typewaranty数组:与例如相同:

$type = ['name' => 'test','company' => '...', 'model' => '...' ]

我尝试这些代码:

$type = $request->input('type.*'); // NULL
and
$type = $request->input('type'); // NULL
and 
$type = Input::get('type'); // NULL
and
$in = $request->all();
$type = $in['type']; // NULL
AND
$request->get('type'); // NULL
AND
$request->post('type') // NULL

不起作用:(,只有我可以通过这种方法获得单个变量:(但我需要数组)

$in = $request->all();
$in['type[code_id]'] ;

而且我测试type[][code_id],,type[][name]...形式但不起作用:(

我的axios方法:

serial = function (id) {
    var srl = $(id).serializeArray();
    var post = {};
    for (const k in srl) {
        let item = srl[k];
        post[item.name] = item.value;
    }
    return post;
}

axios.post(url, serial("#frm")).then(function (res) {// succs axios ;

     console.log(res);
}).catch(err => {// error axios ;
    console.log(err);
}); // end axios ;

Laravel 原生解决方案是什么?对于这个问题?

注意:我可以创建一个函数来解决这个问题,但我需要 laravel 原生解决方案。

标签: phparrayslaravellaravel-5.7

解决方案


您可以使用此函数处理数组:

function categorizedArray($array){
    $ret = [] ;
    $re = '/(.*)\[(.*)\]/U';
    foreach ($array as $i => $value) {
        preg_match_all($re, $i, $matches, PREG_SET_ORDER, 0);
        if ($matches == []){
            $ret[$i] = $value ;
        }else{
            $ret[$matches[0][1]][$matches[0][2]] = $value ;
        }
    }
    return $ret;
}

例如:(我们假设函数定义为助手

$all = categorizedArray($request->all());

推荐阅读