dongtun3328 2013-04-06 04:16
浏览 91

如何从数组中的对象中获取值

I'm trying to get data out of a variable called $items

When I var_dump($items); - the result is like this:

array(13) { 

[0]=> object(stdClass)#868 (2) { 
        ["meta_key"]=> string(17) "Email of Attendee"        
        ["meta_value"]=> string(68) "some-email@gmail.com" 
} 

[2]=> object(stdClass)#804 (2) { 
        ["meta_key"]=> string(28) "Name to be printed on badge:" 
        ["meta_value"]=> string(7) "some name to be printed" 
}

...and so on 11 more times

I want to know if it is possible to get the email from $items with code that something like this:

$email = $items find the object where meta_key has the value "Email of Attendee" then return me the corresponding value.

What I ended up doing was running $items through a foreach loop like so:

foreach($items as $item){

    $items[$item->meta_key]=$item->meta_value;

}

Which converts all the "meta_keys" into the values that they were referencing. now:

$email = $items["Email of Attendee"]  

echo $email; 

result is some-email@gmail.com

Posting this so that a. someone else in a similar jam might use the for each loop that converts things

b. someone with more experience can suggest a way to get the "Email of Attendee directly from the $items, without having to run it through a foreach loop.

  • 写回答

4条回答 默认 最新

  • donglian4770 2013-04-06 04:32
    关注

    Still relying on the use of foreach loop.

    function get_email($items) {
    
        foreach($items as $item){
    
            if (in_array("Email of Attendee", $item) {
                $email = $item["meta_value"];
                break;
            }
    
        }
        return $email;
    }
    

    Correction You can get the particular object with array_filter

    $result = array_filter($array, function($o) {
                       return $o->meta_key == "Email of Attendee";
    });
    
    $email = $result[0]->meta_value;
    
    echo $email;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 vscode问题请教
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM