通过对象内部的键从对象数组获取字段值 [英] Getting field value from object array by key inside object

查看:124
本文介绍了通过对象内部的键从对象数组获取字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常愚蠢的问题,我无法相信我正在询问类似这样的简单问题.

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

我使用db->get['table']->result()从表中获取数据.

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

表架构如下所示:table(id,col1,col2).

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

db->get['table']->result()返回类似以下内容的内容(print_r):

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"
    )
}

现在,我需要从id = 2的行中获取col2值,我想在没有"foreach"循环的情况下做到这一点.

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

我以为我可以这样做:

$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?

推荐答案

嗯,您可以将array_uintersect与仅比较$ id属性的回调函数一起使用,但是有点笨拙,并且可能不会比简单的for循环快

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.

也许我们应该从另一个角度出发...也许找到正确记录的最有效方法是在数据库上触发SELECT查询-毕竟这正是针对数据库进行了优化的对象,尤其是作为id的对象列将被索引(假设id是主键).

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).

原始帖子:

我认为它不仅简单:

I assume it's not just as simple as:

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

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

这篇关于通过对象内部的键从对象数组获取字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆