【问题标题】:How to get a specific value out an an array of objects in PHP [duplicate]如何从PHP中的对象数组中获取特定值[重复]
【发布时间】:2018-05-22 23:15:36
【问题描述】:

我有以下数组,并且正在尝试获取具有 license_number 元密钥的对象的元值。如何返回该值?

items: [
{
    account_id: "7890",
    t: 1990007,
    meta_value: "27",
    id: "123",
    create_date: 1507174015113,
    update_date: 1512628710384,
    meta_key: "content_items",
},
{
    account_id: "7890",
    t: 1990007,
    meta_value: "123456",
    id: "123",
    create_date: 1498492590855,
    update_date: 1498492590855,
    meta_key: "location_id",
},
{
    account_id: "7890",
    t: 1990007,
    meta_value: "123456789",
    id: "123",
    create_date: 1498492590855,
    update_date: 1498492590855,
    meta_key: "license_number",
}
]

【问题讨论】:

  • 循环它,使用 if 语句.. 基本的东西。你有没有采取措施试图找出答案?你的尝试在哪里?您是否在 Google 上搜索过“如何访问对象”?叹息
  • 请查看3v4l.org/sMlho

标签: php


【解决方案1】:

使用 array_filter() 和一个可满足您需求的可调用对象(此处为匿名函数):

$searchedValue = 'license_number';
$o = array_filter( $items,
    function ($e) use (&$searchedValue) {
        return $e->meta_key == $searchedValue;
    }
);

请注意,返回是一个对象数组,其中包含符合条件的所有值。这将为您提供第一个结果。

reset($o); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-01
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多