Getting field value from object array by key inside object

蓝咒 提交于 2019-12-13 07:26:54

问题


This is very stupid question and I can't believe that im asking about something simple like this.

Im using db->get['table']->result() to get data from table.

Table schema looks like this: table(id, col1, col2).

db->get['table']->result() returns something like this (print_r):

Array
(
[0] => stdClass Object
    (
        [id] => 1
        [col1] => "id 1 col 1"
        [col2] => "id 1 col 2"
    )

[1] => stdClass Object
    (
        [id] => 2
        [col1] => "id 2 col 1"
        [col2] => "id 2 col 2"
    )

[2] => stdClass Object
    (
        [id] => 3
        [col1] => "id 3 col 1"
        [col2] => "id 3 col 2"
    )
}

Now i need to get col2 value from row that has id=2, i want to do it without "foreach" loop.

I thought i can do it like this:

$valueThatINeed = $myArray[2]->col2;

This is wrong and i know why its wrong.

Question is - how to directly get that what i need without loop?


回答1:


my_filter($array,$ID) {
     $col2 = array_values(array_filter($array, function($arrayValue) use($ID) { return $arrayValue[0] == $ID; } ));
     if (count($col2) > 0) {
        return $col2[0][2];
     } else {
        return false;
    }
}

$col2 = my_filter($arr,2);



回答2:


Hmm, you could probably use array_uintersect with a callback function that compares just the $id property but it's a bit clumsy, and probably no faster than a simple for loop.

Perhaps we should come at this from a different angle... Probably the most efficient way to find the right record is to fire a SELECT query at the database - after all that's exactly what databases are optimised for, especially as the id column will be indexed (assuming id is the primary key).

Original post:

I assume it's not just as simple as:

$valueThatINeed = $myArray[2]->$col2;



来源:https://stackoverflow.com/questions/13098163/getting-field-value-from-object-array-by-key-inside-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!