【问题标题】:Cakephp collection how can I get array index?Cakephp 集合如何获取数组索引?
【发布时间】:2021-07-20 13:20:01
【问题描述】:

这是我的收集数据

[
   0 => object(App\Model\Entity\SummaryCoin) id:0 { 'user_id' => (int) 2
'total_sum_coin' => (float) 3 },
   1 => object(App\Model\Entity\SummaryCoin) id:1 { 'user_id' => (int) 1
'total_sum_coin' => (float) 33 },
]

如何获取user_id = 1所在的索引

使用第一个匹配我可以获得用户 1 的新集合

$sumOfUserCoins = $collection->firstMatch([
    'user_id' => 1
]);

如何获取用户拥有的数组索引1

【问题讨论】:

    标签: cakephp cakephp-4.x


    【解决方案1】:

    没有特定的方法,您必须有一点创意才能获取该信息,例如匹配所有而不是这样您就可以得到一个集合,把所有东西都拿走,除了第一个条目,然后转换它到一个保存键的数组,然后您可以从中获取该信息:

    $userCoins = $collection
        ->match(['user_id' => 1])
        ->take(1)
        ->toArray();
    
    $index = key($userCoins);
    $coin = current($userCoins);
    

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 2019-10-01
      相关资源
      最近更新 更多