foreach循环获取元素的值

时间:2014-11-12 00:37:11

标签: php

在过去的几个小时里,我一直在努力解决这个问题,一直在努力从这个数组中获取userid和jobprocstatus的价值。

这是 print_r($ result);

的结果
 stdClass Object ( [accountid] => 6f3f55f6-67a1-11e4-a7c1-7e542e26bbf0 [userid] => 6f3f650b-67a1-11e4-a7c1-7e542e26bbf0 [cmd] => org.apache.cloudstack.api.command.admin.vm.DeployVMCmdByAdmin [jobstatus] => 1 [jobprocstatus] => 0 [jobresultcode] => 0 [jobresulttype] => object [jobresult] => stdClass Object ( [virtualmachine] => stdClass Object ( [id] => ccfbb592-ebfa-4f18-b861-4ae5e1a15426 [name] => VM-ccfbb592-ebfa-4f18-b861-4ae5e1a15426 [displayname] => VM-ccfbb592-ebfa-4f18-b861-4ae5e1a15426 [account] => admin [domainid] => ea3b19e6-67a0-11e4-a7c1-7e542e26bbf0 [domain] => ROOT [created] => 2014-11-11T17:39:31-0500 [state] => Running [haenable] => [zoneid] => 481b2bdf-90ba-4841-bd5a-f4fbf6027401 [zonename] => Toronto [hostid] => cc66aa5e-6be3-4f35-b538-87a9b09a6fc5 [hostname] => TOR-XENSRV61 [templateid] => ea41cab5-67a0-11e4-a7c1-7e542e26bbf0 [templatename] => CentOS 5.6(64-bit) no GUI (XenServer) [templatedisplaytext] => CentOS 5.6(64-bit) no GUI (XenServer) [passwordenabled] => [serviceofferingid] => 61ee4943-1af5-4168-9dee-fdd128fd58db [serviceofferingname] => Small Instance [cpunumber] => 1 [cpuspeed] => 500 [memory] => 512 [guestosid] => ea9ebb7a-67a0-11e4-a7c1-7e542e26bbf0 [rootdeviceid] => 0 [rootdevicetype] => ROOT [securitygroup] => Array ( ) [nic] => Array ( [0] => stdClass Object ( [id] => 1145aa85-cf95-4215-b1a7-439166698c23 [networkid] => fdeaaf3a-2ee1-45e3-bc15-b325b2ea517c [networkname] => test [netmask] => 255.255.255.0 [gateway] => 192.168.168.1 [ipaddress] => 192.168.168.177 [isolationuri] => vlan://286 [broadcasturi] => vlan://286 [traffictype] => Guest [type] => Isolated [isdefault] => 1 [macaddress] => 02:00:6d:ba:00:16 ) ) [hypervisor] => XenServer [instancename] => i-2-29-VM [tags] => Array ( ) [affinitygroup] => Array ( ) [displayvm] => 1 [isdynamicallyscalable] => 1 [ostypeid] => 142 [jobid] => 3a3c2e81-296b-4f00-906d-d4aac918487c [jobstatus] => 0 ) ) [created] => 2014-11-11T17:39:32-0500 [jobid] => 3a3c2e81-296b-4f00-906d-d4aac918487c ) 

这就是我试过的

<?php 

foreach ($result as $key => $value) {
    echo "$key : $value <br>";

}

输出

accountid : 6f3f55f6-67a1-11e4-a7c1-7e542e26bbf0 
userid : 6f3f650b-67a1-11e4-a7c1-7e542e26bbf0 
cmd : org.apache.cloudstack.api.command.admin.vm.DeployVMCmdByAdmin 
jobstatus : 1 
jobprocstatus : 0 
jobresultcode : 0 
jobresulttype : object 

我只是试图从这个数组中获取userid元​​素的值,但每次我尝试

echo "$result['userid']";

我收到银行屏幕,我无法确定问题所在。

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:5)

这可以解决对象列表

foreach ($result as $key => $value) {
    echo $value->userid;
}

对于单个对象:

echo $value->userid;

$value是一个对象,要获取对象的属性,必须使用->运算符。

如果要获取对象列表的所有公共属性:

foreach ($result as $key => $obj) {
    foreach (get_object_vars($obj) as $name => $value) {
        echo "Object mapped to $key has property $name => $value";
    }    
}

答案 1 :(得分:2)

有了这个,您可以访问您的用户ID:

echo $result->userid;