3 回答

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個贊
在PHP中,您有不同的方法來定義array.
一種方法是通過顯式設(shè)置其值來定義它,例如:
<?php
$my_array_1 = array("first" => 0, "second" => 1) // or;
$my_array_2 = array(0, 1, 2);
?>
數(shù)組可以存儲混合值,因此這是有效的:
<?php
$my_array_3 = array(0, "one", 2)
?>
你的數(shù)組就像之前的數(shù)組一樣:
<?php
$items_arrays = array($request['itemsArray'], true);
?>
PHP沒有參數(shù),只有添加的項目,因此您放在末尾的只是數(shù)組的第二個元素 。 https://www.php.net/manual/en/function.array.phparray()true
基于此,您的dd輸出與定義數(shù)組時添加的內(nèi)容完全相同:
array:2 [
0 => "{"1":[2],"2":[1,3]}" // this is the string from $request['itemsArray']
1 => true // this is the second element you added
]
我認(rèn)為你的問題是你需要解析string你在$request['itemsArray'].
所以,首先:
public function itemsStore(Request $request)
{
$json = json_decode($request['itemsArray']);
// $json is now an associative array in PHP
// something like: array(1 => array(2), 2 => array(1, 3))
// $items_arrays = array($request['itemsArray'], true);
// dd(items_arrays);
}
然后你需要展平這個關(guān)聯(lián)數(shù)組:
public function itemsStore(Request $request)
{
$json = json_decode($request['itemsArray']);
// $json is now an associative array in PHP
// something like: array(1 => array(2), 2 => array(1, 3))
$items_arrays = [];
foreach(json as $key1 => $val1) {
foreach($val1 as $key2 => $val2) {
$items_array[] = array($key1 => $val2);
}
}
// $items_arrays = array($request['itemsArray'], true);
dd(items_arrays);
}
(json_decode有可選參數(shù):https://www.php.net/manual/en/function.json-decode.php)
當(dāng)然,您應(yīng)該$request在使用它之前檢查 - 身份驗(yàn)證和驗(yàn)證很重要!
抱歉,如果語法不正確 - 我已經(jīng)一年多沒有使用 PHP 了,并且用心編寫了示例(沒有檢查)。但這個想法肯定是正確的:
從請求中獲取數(shù)據(jù)(驗(yàn)證數(shù)據(jù)!這不是流程所必需的,但生產(chǎn)環(huán)境需要?。?/p>
將其從字符串格式轉(zhuǎn)換為 PHP 數(shù)組
在最終數(shù)組中讀取它(因?yàn)槟罱K需要它)
將最終的格式存入數(shù)據(jù)庫

TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個贊
您需要為動態(tài)選擇指定一些名稱。例如,如果您有一個屬性列表 [尺寸,顏色],您可以執(zhí)行以下操作
...
...
在服務(wù)器端您將收到一個數(shù)組 param attr[]
$attr = 請求()->attr;
它應(yīng)該看起來像 $attr['size'] => [ 您選擇的尺碼] $attr['color'] => 您選擇的顏色。
您可以轉(zhuǎn)儲來觀看表格。
我希望它有幫助,請告訴我。

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超5個贊
嘗試這個替代方案
確保在 html 中將 name 屬性設(shè)置為如下所示的數(shù)組
<select multiple="multiple" name="sizes[]" id="sizes">
然后要存儲它,您可以將其放入控制器中,例如
$sizes = $request->input('sizes');//it will give you string separated by commas
$sizes = explode(',', $sizes);// to separate it explode the string
// save it to database
同樣,對于其他輸入(例如多選顏色輸入),您可以使用上述步驟
- 3 回答
- 0 關(guān)注
- 173 瀏覽
添加回答
舉報