如何從 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
廣告