简体   繁体   English

Laravel从集合中获取价值

[英]Laravel get values from collection

If collection is created from an array: 如果从数组创建集合:

$collection = collect();
$collection->push([
        'var1'=>'value1',
        'var2'=>'value2'
       ]);

is there possibility to get value for specific key similar way to eloquent collection attributes? 是否有可能以与雄辩的收藏属性类似的方式获取特定键的价值?

$collection->var1

My variant: 我的变体:

$collection = collect();
$collection->push([
    'var1'=>'value1',
    'var2'=>'value2'
]);
$value = $collection->get('var1'); // value1

https://laravel.com/docs/5.6/collections#method-get https://laravel.com/docs/5.6/collections#method-get

No, but you can definitely do something like 不,但是您绝对可以做类似的事情

$collection->first(function($value, $key) {
  return $key == 'var1';
});

or simply what @AlexeyMezenin suggested. 或@AlexeyMezenin的建议。

$collection[0]['var1'];

My personal touch though I am still learning the basics myself so don't shoot me down for trying! 我的个人风格虽然我仍在学习基础知识,所以请不要因为尝试而失望! I know its a little extra code but from experience you can get caught out with offset exception errors when calling $collection[0] explicitly (Hope I am making sense as this has been a personal gotcha experience) 我知道它有一些额外的代码,但是从经验来看,当您显式调用$collection[0]时,您可能会遇到偏移异常错误(希望我有道理,因为这是个人的陷阱经验)

My approach would be the following 我的方法如下

$collection = collect();
$collection->push([
    'var1'=>'value1',
    'var2'=>'value2'
]);

for ($x = 0; $x < count($collection); $x++) {
    if (isset($collection[$x])) {
        $var = $collection[$x];
    }
}

// Now call what ever variable from the collection you wish:

echo $var['var1'];
echo $var['var2'];

Hope that helps, Like I said though I am far from experienced with php/laravel and I am still learning from research myself :) 希望能有所帮助,就像我说的那样,尽管我对php / laravel的经验还很远,但我仍在从研究中学习:)

To set a key'd value in a collection you can use the put() method. 要在集合中设置键值,可以使用put()方法。

$collection = collect();

$collection->put("var1", "value1");
$collection->put("var2", "value2");
$collection->put("var3", "value3");

To push just a value without a key to the collection, use the push() method, like you did in the OP. 要仅将没有键的值推送到集合,请像在OP中一样使用push()方法。

$collection->push("value4");

To retrieve those value, use get() method; 要获取这些值,请使用get()方法;

$collection->get("var2");

Want to see the contents of the collection? 想看收藏的内容吗? Use the dd() method on the collections instances. 在集合实例上使用dd()方法。 Both of the following work. 以下两项工作。

dd($collection)

or 要么

$collection->dd()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM