laravel collections-> keyBy找到类似的键

时间:2017-10-04 10:20:11

标签: php laravel collections

laravel 5.5 这是收藏品:

$collections = collect(['name' => 'Rob'], ['nickname' => 'Robby']);

这两种方法:

$collections->keyBy('name')
$collections->keyBy('nickname')

返回equil结果

Collection {#246 ▼
  #items: array:1 [▼
    "" => "Rob"
  ]
}

就像我这看起来错了......

3 个答案:

答案 0 :(得分:1)

我认为你应该将一个参数作为数组传递..试试这个

$collections = collect([['name' => 'Rob'], ['nickname' => 'Robby']]);

答案 1 :(得分:0)

所以结果是

Collection {#246 ▼
  #items: array:2 [▼
    "Rob" => array:1 [▼
      "name" => "Rob"
    ]
    "" => array:1 [▼
      "nickname" => "Robby"
    ]
  ]
}

Collection {#246 ▼
  #items: array:2 [▼
    "" => array:1 [▼
      "name" => "Rob"
    ]
    "Robby" => array:1 [▼
      "nickname" => "Robby"
    ]
  ]
}

在集合中搜索仍然无效... 和

$collections->keyBy('nick')

返回

Collection {#246 ▼
  #items: array:1 [▼
    "" => array:1 [▼
      "nickname" => "Robby"
    ]
  ]
}

答案 2 :(得分:0)

您的问题是您的收藏品格式不正确,请执行以下操作:

$collections = collect([ //main collection array
            [ 'name' => 'Rob1', 'nickname' => 'Robby1' ] //object 0 inside collection array with well formated keys => values
        ]);

现在使用时:

$collections->keyBy('name')
$collections->keyBy('nickname')

它将按指定的方式工作