从 Laravel 中的对象数组中获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45210136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get a value from within an array of object in Laravel
提问by Soumya Rauth
I am quite new no laravel. I know that it is a pretty basic question. But, I still can't figure it out. Heres my Array output and I want to get the value of name from within this array. This is the output I get in postman after I used print_r:
我很新没有laravel。我知道这是一个非常基本的问题。但是,我还是想不通。这是我的数组输出,我想从这个数组中获取 name 的值。这是我在使用 print_r 后在邮递员中得到的输出:
Array
(
[0] => Array
(
[name] => Test 2322
[id] => 4
)
)
回答by Karthik
if you want all of them
如果你想要所有的
foreach ($datas as $datavals) {
echo $datavals['name'];
}
If you want 0 array name element value Just call following :
如果你想要 0 数组名称元素值只需调用以下:
echo $memus[0]['name'];
回答by ka_lin
In case this is a collectionyou can use the pluckmethod
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']
If in your case you do not have a collection you can create it with the collectmethod.
如果在您的情况下您没有集合,则可以使用collect方法创建它。
In your case:
在你的情况下:
$myarray = collect($initialArray); //You can ignore this if it is already an array
$nameArray = $myarray->pluck('name')->all();
foreach($nameArray as $name)
{
echo $name; //Test 2322
}
回答by Sagar Gautam
You can iterate the array with foreach
on blade and get index="name"
for each entry like this:
您可以使用foreach
on Blade迭代数组并获取index="name"
每个条目,如下所示:
In View
在视图中
@foreach($data as $d)
{{$d['name']}}
@endforeach
In Controller
在控制器中
foreach($data as $d){
// This is the value you want
$name = $d['name']
}
回答by stuti
Simply write the array name with the indices and key which have to access.Suppose $a[] is array then $a[0]['name'] and the value at zero index of array will be retrieved or you can parse it in loop which will give the value of key ['name'] at every indices.
foreach($a as $item)
{
print_r($item['name']);
}