如何在 laravel 中的数组对象中添加键值对
How to add key value pair in objects of array in laravel
我正在关注 laravel 中的输出。
[ {"id":"1","name":"Mite Salary"}, {"id":"2","name":"Riky"}, {"id":"3","name":"Raj"} ]
我想添加另一个键值对 age:person_age 并希望输出为
[ {"id":"1","name":"Mite Salary", "age":'20'}, {"id":"2","name":"Riky", "age":'25'}, {"id":"3","name":"Raj", "age":"40"} ]
这个年龄来自 mysql 数据库 $y = DB::table("age")->get();
现在考虑 $y=[20,25,40];
但我不知道如何使用 foreach 循环来完成它。请帮助我。感谢期待
你所做的这不是很好的逻辑,因为你无法知道每个人的年龄,因为人和年龄没有联系如果一个人被删除会发生什么,你将删除相同的年龄 id
?你应该做关系:
1)将age_id
加到你的人table
2) 到 Person
模型添加关系
public function age()
{
return $this->belongsTo('App\Age');
}
3) 现在当你使用 $person->age->"Name of coulmn"
如果你还想这样做,这里是方法
$i = 0;
foreach($pearsons as $person) {
$person->age = $age[$i]
$i++
}
实际上我所做的是将 foreach 循环用于:
$x = [ {"id":"1","name":"Mite Salary"}, {"id":"2","name":"Riky"}, {"id":"3","name":"Raj"} ]
在那个 foreach 循环中我使用了
$x[$x]->age = implode(",",$y[$key]);
最终代码为:
foreach($x as $key => $value) {
$x[$key]->av = implode(",",$y[$key]);
}
你会做这样的事情。假设你有一组 Persons
$persons = [
{
"id" : "1",
"name":"Mite Salary"
},
{
"id" : "2",
"name":"Riky"
},
{
"id" : "3",
"name":"Raj"
}
];
foreach ($persons as $person) {
$person['age'] = TableName::where("id","=", "$person->id" )->get('age');
}
我正在关注 laravel 中的输出。
[ {"id":"1","name":"Mite Salary"}, {"id":"2","name":"Riky"}, {"id":"3","name":"Raj"} ]
我想添加另一个键值对 age:person_age 并希望输出为
[ {"id":"1","name":"Mite Salary", "age":'20'}, {"id":"2","name":"Riky", "age":'25'}, {"id":"3","name":"Raj", "age":"40"} ]
这个年龄来自 mysql 数据库 $y = DB::table("age")->get();
现在考虑 $y=[20,25,40];
但我不知道如何使用 foreach 循环来完成它。请帮助我。感谢期待
你所做的这不是很好的逻辑,因为你无法知道每个人的年龄,因为人和年龄没有联系如果一个人被删除会发生什么,你将删除相同的年龄 id
?你应该做关系:
1)将age_id
加到你的人table
2) 到 Person
模型添加关系
public function age()
{
return $this->belongsTo('App\Age');
}
3) 现在当你使用 $person->age->"Name of coulmn"
如果你还想这样做,这里是方法
$i = 0;
foreach($pearsons as $person) {
$person->age = $age[$i]
$i++
}
实际上我所做的是将 foreach 循环用于:
$x = [ {"id":"1","name":"Mite Salary"}, {"id":"2","name":"Riky"}, {"id":"3","name":"Raj"} ]
在那个 foreach 循环中我使用了
$x[$x]->age = implode(",",$y[$key]);
最终代码为:
foreach($x as $key => $value) {
$x[$key]->av = implode(",",$y[$key]);
}
你会做这样的事情。假设你有一组 Persons
$persons = [
{
"id" : "1",
"name":"Mite Salary"
},
{
"id" : "2",
"name":"Riky"
},
{
"id" : "3",
"name":"Raj"
}
];
foreach ($persons as $person) {
$person['age'] = TableName::where("id","=", "$person->id" )->get('age');
}