如何從 PHP 物件中列印鍵?


假設以下為我們的物件 -

$employeeDetails = (object) [
    'firstName' => 'John',
    'lastName' => 'Doe',
    'countryName' => 'US'
];

我們想要下面這種輸出,即只顯示鍵 -

firstName
lastName
countryName

若要在 PHP 中僅顯示物件中的鍵,請使用 array_keys()。

示例

 線上演示

<!DOCTYPE html>
<html>
<body>
<?php
$employeeDetails = (object) [
   'firstName' => 'John',
   'lastName' => 'Doe',
   'countryName' => 'US'
];
$allKeysOfEmployee = array_keys((array)$employeeDetails);
echo "All Keys are as follows=","<br>";
foreach($allKeysOfEmployee as &$tempKey)
echo $tempKey,"<br>";
?>
</body>
</html>

輸出

All Keys are as follows=
firstName
lastName
countryName

更新於:2020 年 10 月 12 日

5K+ 次閱讀

開啟你的 職業

完成課程以獲得認證

開始
廣告