convert to array then get keys and valus
In PHP, you can use various functions and methods to retrieve keys and values from an object. Here are a few commonly used approaches:
get_object_vars()
function: Theget_object_vars()
function returns an associative array that contains the object's properties and their respective values. Here's an example:
$object = new stdClass();
$object->name = "John";
$object->age = 25;
$properties = get_object_vars($object);
$keys = array_keys($properties);
$values = array_values($properties);
// Output the keys
print_r($keys);
// Output the values
print_r($values);
s
output
Array
(
[0] => name
[1] => age
)
Array
(
[0] => John
[1] => 25
)
s
foreach
loop:
You can iterate over the object using a foreach
loop to access its properties and their values. Here's an example:$object = new stdClass();
$object->name = "John";
$object->age = 25;
$keys = [];
$values = [];
foreach ($object as $key => $value) {
$keys[] = $key;
$values[] = $value;
}
// Output the keys
print_r($keys);
// Output the values
print_r($values);
s
s
s
Array
(
[0] => name
[1] => age
)
Array
(
[0] => John
[1] => 25
)
s
These examples demonstrate how to retrieve the keys and values from an object in PHP using
get_object_vars()
or iterating over the object with a foreach
loop. Choose the approach that best fits your needs and the structure of your object.$keys = array_keys((array)$BIRD);
$array = get_object_vars($object);
$properties = array_keys($array);
No comments:
Post a Comment