9

好的,我们开始吧。我希望我能正确解释这一点。

我有一个对象,我想循环获取键和值。这是我收到的对象的示例。提前感谢您的任何帮助或想法。

    Array
(
    [0] => stdClass Object
        (
            [id] => 93
            [RecordGUID] => 
            [txtEmplid] => 0134754
            [txtFname] => 
            [txtLname] => 
            [txtMname] => 
            [txtEmail] => 
            [txtSecEmail] => 
            [txtPhoneNo] => 4046565454
            [drpMajor] => 
            [drpStatus] => 
            [regmain] => 
            [chkDental] => 0
            [chkDO] => 
            [chkMD] => 
            [chkMDPHD] => 
            [chkNursin] => 
            [chkOPT] => 
            [chkPA] => 
            [chkPH] => 
            [chkPharm] => 
            [chkPOD] => 
            [chkPostBac] => 
            [chkVet] => 
        )

)

我基本上需要遍历上述信息来获取键和值。例如:

id=93
RecordGUID=
txtEmplid=0134754

等等。

再次,提前感谢任何答案。

DBF 的更新这是我使用您的代码片段时得到的结果:

int(0)
object(stdClass)#27 (24) {
  ["id"]=>
  string(2) "93"
  ["RecordGUID"]=>
  NULL
  ["txtEmplid"]=>
  string(7) "0134754"
  ["txtFname"]=>
  string(0) ""
  ["txtLname"]=>
  string(0) ""
  ["txtMname"]=>
  string(0) ""
  ["txtEmail"]=>
  string(0) ""
  ["txtSecEmail"]=>
  string(0) ""
  ["txtPhoneNo"]=>
  string(10) "4045506561"
  ["drpMajor"]=>
  NULL
  ["drpStatus"]=>
  NULL
  ["regmain"]=>
  NULL
  ["chkDental"]=>
  string(1) "0"
  ["chkDO"]=>
  NULL
  ["chkMD"]=>
  NULL
  ["chkMDPHD"]=>
  NULL
  ["chkNursin"]=>
  NULL
  ["chkOPT"]=>
  NULL
  ["chkPA"]=>
  NULL
  ["chkPH"]=>
  NULL
  ["chkPharm"]=>
  NULL
  ["chkPOD"]=>
  NULL
  ["chkPostBac"]=>
  NULL
  ["chkVet"]=>
  NULL
}
4

2 回答 2

25

利用get_object_vars ( object $object )

$vars = get_object_vars ( $object );
foreach($vars as $key=>$value) {
  var_dump($key);
  var_dump($value);
}

或者只是迭代对象本身

foreach($object as $key=>$value) {
  var_dump($key);
  var_dump($value);
}

-- 编辑 2

在这里,您将在一行中拥有键和值

$string = "";
foreach($regs as $object) {
  foreach($object as $key=>$value) {
    $string += "{$key}={$value} ";
  }
}
echo $string;

如果这不是你需要的,我一无所知..

于 2012-09-08T23:08:37.387 回答
2

您可以遍历对象属性foreach

foreach($array as $key => $object)
    foreach($object as $property => $value)
        echo "{$property} : $value" . PHP_EOL;
于 2012-09-08T23:08:03.983 回答