[英]How to inser an array value to array in Laravel PHP
The data column of user table is as follows.用户表的数据列如下。
data | {"user": [["id", true], ["name", true], ["email", true], ["address", true], ["dob", true]], "prime_user": [["id", true], ["name", true], ["email", true], ["address", true], ["dob", true]], "premium_user": [["id", true], ["name", true], ["email", true], ["address", true], ["dob", true]]}
Now for this data, I want to add another value ["first_name", true]
next to the id, to each array(user, prime_user, premium_user) of these data.现在对于这些数据,我想在 id 旁边添加另一个值
["first_name", true]
到这些数据的每个数组(user、prime_user、premium_user)。 ie I want to update the above value as below即我想更新上面的值如下
{
"user":[
[
"id",
true
],
[
"first_name",
true
],
[
"name",
true
],
[
"email",
true
],
[
"address",
true
],
[
"dob",
true
]
],
"prime_user":[
[
"id",
true
],
[
"first_name",
true
],
[
"name",
true
],
[
"email",
true
],
[
"address",
true
],
[
"dob",
true
]
],
"premium_user":[
[
"id",
true
],
[
"first_name",
true
],
[
"name",
true
],
[
"email",
true
],
[
"address",
true
],
[
"dob",
true
]
]
}
I have tried something like this, but it is not working.我已经尝试过这样的事情,但它不起作用。 Can anyone help me out?
谁能帮我吗? Thanks.
谢谢。
$data = $user->data;
$inserted = array("first_name", true);
foreach ($data as $d) {
array_splice($d, 1, 0, $inserted );
}
$user->data = $data;
$user->save();
array_splice uses the reference but you are using $d which is a local variable for the loop and it doesn't affect the $data variable. array_splice 使用引用,但您使用的是 $d ,它是循环的局部变量,它不会影响 $data 变量。
try using array_splice($data[$key], ... )
instead, add $key
in loop like this: foreach($data as $key => $d)
尝试使用
array_splice($data[$key], ... )
代替,在循环中添加$key
,如下所示: foreach($data as $key => $d)
Change your loop like this and you will get your result像这样改变你的循环,你会得到你的结果
foreach($data as $key => $value)
{
$data[$key] = array_merge(array_slice($value, 0, 1),[$inserted ],array_slice($value, 1));
}
may it helps....可能有帮助....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.