PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 3, 2022

[FIXED] Cakephp collection how can I get array index?

 February 03, 2022     cakephp, cakephp-4.x     No comments   

Issue

This is my collection data

[
   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 },
]

How can I get the index where user_id = 1

Using first match I am able to get user 1 new collection

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

How I will get the array index 1 that user have ?


Solution

There is no specific method for that, you'll have to be a little creative to obtain that information, for example match all instead so that you get a collection back, take everything away expect for the first entry, and convert it to an array that keeps the keys, from which you can then get that information:

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

$index = key($userCoins);
$coin = current($userCoins);


Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing