从Laravel中的对象数组中获取值

时间:2017-07-20 09:04:45

标签: php laravel

我很新,没有laravel。我知道这是一个非常基本的问题。但是,我仍然无法弄明白。继承我的数组输出,我想从这个数组中获取name的值。这是我使用print_r后在postman中得到的输出:

@RestController

4 个答案:

答案 0 :(得分:3)

如果你想要所有这些

foreach ($datas as $datavals) {
       echo $datavals['name'];
}

如果你想要0数组名元素值,请调用以下:

   echo $memus[0]['name'];

答案 1 :(得分:1)

您可以在刀片上使用foreach迭代数组,并为每个条目获取index="name",如下所示:

在视图中

@foreach($data as $d)

   {{$d['name']}}

@endforeach

在控制器

foreach($data as $d){

   // This is the value you want
   $name = $d['name']

}

答案 2 :(得分:0)

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']);
}

答案 3 :(得分:0)

如果这是collection,您可以使用pluck方法

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

$plucked = $collection->pluck('name');

$plucked->all();
// ['Desk', 'Chair']

如果您没有收藏品,可以使用收集方法创建收藏品。

在你的情况下:

$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
}