【问题标题】:Get html form values and convert to Json array Laravel获取 html 表单值并转换为 Json 数组 Laravel
【发布时间】:2019-04-18 12:48:33
【问题描述】:


在我看来,我有一个这样的表格:

<form action="http://localhost/RenderForm/public/handle-form" method="POST">
    <input type="hidden" name="_token" value="BOwsdSS3Zc4oI08wDutUQbvtQhGvGZXBgxaOoOFD">                                                                    
    <div class="links">
        <div>
	        First Name:<br>
	        <input name="firstName" type="text">
        </div>        
        <br>
    </div>
                                                
    <div class="links">
        <div>
	        Last Name:<br>
	        <input name="lastName" type="text">
        </div>        
        <br>
    </div>
                                                
    <div class="links">
        <div>
	        Location:<br>
	        <select name="location">
				<option value="0">HN</option>
				<option value="1">HCM</option>
			</select>
        </div>        
        <br>
    </div>
                                            
    <div>
        <button type="submit">Reset Form</button>
        <button type="submit">Complete Task</button>
    </div>
</form>

在我的控制器中,我使用 $request->all() 来获取所有表单值并存储到一个变量中。之后,我使用 json_encode 将其转换为 Json 对象。
当我调试该变量时,它具有值:

"{"firstName":"hao","lastName":"nguyen","location":"0"}"

但我真正需要的是:

[ { “id”:“名字”, “价值”:“豪” }, { “id”:“姓氏”, “价值”:“阮” }, { “id”:“位置”, “价值”:“0” } ]

你能告诉我如何解决这个问题吗?非常感谢!

【问题讨论】:

  • 试试$arr = [json_decode(json_encode($request-&gt;all()), true)];
  • array:1 [▼ 0 => array:4 [▼ "_token" => "RKvYNS7ubX4x2AGGxSU7Rwp6ClYJnnq4TSr1ob8c" "firstName" => "hao" "lastName" => "nguyen" "location" => “0”]]
  • 这不是我需要的

标签: html laravel


【解决方案1】:

使用 foreach 循环并像这样自定义所有输入:

$collect = []; // empty array for collect customised inputs

foreach($request->all() as $input_key => $input_value){ // split input one by one

     $collect[] = array( //customised inputs
            "id" => $input_key,
            "value" => $input_value

     );
} 

$result = json_encode($collect); //convert to json

【讨论】:

  • 正是我需要的。非常感谢!你拯救了我的一天:))
猜你喜欢
  • 2017-09-11
  • 2023-03-28
  • 2011-11-21
  • 2015-02-18
  • 2011-08-12
  • 1970-01-01
  • 2021-11-17
  • 2012-09-13
  • 2020-07-16
相关资源
最近更新 更多