Welcome Guest, Not a member yet? Register   Sign In
Query result as an indexed array or object by index of choice
#1

(This post was last modified: 04-23-2020, 02:59 AM by Leo.)

Very often I need to index my array or object by a certain key like this:
PHP Code:
$unindexed $model->select('id, filter_id, value_name')
    ->whereIn('id', [1,2,3,4])
    ->orderBy('id''ASC')
    ->findAll();

$indexed = [];
foreach(
$unindexed as $i) {
   $indexed[$i->id] = $i;

process can be simplified with array_column:
PHP Code:
$indexed array_column($unindexednull'id'); 

What about a built in function in a model? like this:
PHP Code:
$indexed $model->select('id, filter_id, value_name')
            ->whereIn('id', [1,2,3,4])
            ->orderBy('id''ASC')
            ->getResultKey('id'); 

So far I have a blunt copy of findAll():
PHP Code:
public function getResultKey(string $keyint $limit 0int $offset 0)
{
      return array_column($this->findAll($limit$offset), null$key);


It works as expected, it can return an array of arrays or objects depending on your models returnType. Also it can use integer or string key for indexing. But, with it being just a copy of findAll() it seems like bloatware.

If anyone has better ideas of how to implement this, or if you think its worth it, or make it chain with other methods that would be nice. Otherwise, I can usually just do this:
PHP Code:
$indexed array_column($model->select('id, filter_id, value_name')
            ->whereIn('id', [1,2,3,4])
            ->orderBy('id''ASC')
            ->findAll(), null'id'); 
You can see things I made with codeigniter here: itart.pro its not overly impressive as I have very little time to learn.
Reply


Messages In This Thread
Query result as an indexed array or object by index of choice - by Leo - 04-22-2020, 12:04 PM



Theme © iAndrew 2016 - Forum software by © MyBB