嘗試使用array_values,但它只是暫時的。Laravel,如何永久更改數組密鑰?
控制器
foreach($rows as $key => $value)
{
array_values($value);
//dd shows the key changes to [0], [1], [2] and so on
}
嘗試使用array_values,但它只是暫時的。Laravel,如何永久更改數組密鑰?
控制器
foreach($rows as $key => $value)
{
array_values($value);
//dd shows the key changes to [0], [1], [2] and so on
}
你可以像這樣做,
$rows = array_map(function($v){return array_values($v);}, $rows);
哦,很好...漂亮整潔 – begineeeerrrr
'array_map('array_values',$ rows)'也可能工作 – apokryfos
更美麗,好看! – begineeeerrrr
像這樣的東西應該工作:
$new = [];
foreach($rows as $key => $value)
{
array_values($value);
$sub = [];
foreach ($value as $subKey => $subValue) {
$subKey = $key;
$sub[$key] = $subValue;
}
$new[$key] = $sub;
//dd shows the key changes to [0], [1], [2] and so on
}
然後返回$new
而不是$rows
。
嗯......除此之外還有其他選擇嗎?或者有這樣一個雄辯的方式嗎? – begineeeerrrr
不要更改數組鍵。代碼可以變得更清潔,但我現在在工作,所以沒有時間。你可以使用上面的作爲基礎和清理它一下,然後編輯答案也許? – DrRoach
好吧,我會在等待清潔版時首先使用它 – begineeeerrrr
如果你試圖改變關聯數組索引數組,這樣做:
$array = array_values($array);
無需複雜的事情。 – GoogleMac
不會改變任何東西 – begineeeerrrr
@benineeeerrrr它實際上完全是你想要的。看到這裏:https://code.sololearn.com/wF6d755yf5gG – GoogleMac
由於您使用laravel可以也可以這樣做:
$rows = collect($rows)->map(function ($value) {
return Arr::accessible($value)?collect($value)->values()->all():$value;
})->all();
你是什麼意思永久?你想要保存數組嗎?如果是這樣,您需要將數據存儲在數據庫中。 – DrRoach
如果我通過它來查看緊湊($行);並在視圖中使用它,它將更改爲正常 – begineeeerrrr
當前數組中的鍵是什麼?你想讓他們設置爲什麼? – DrRoach