I have a PHP object that I need to change the key name of in a foreach loop:
stdClass Object
(
[first-name] => NAME
[last-name] => NAME
[phone-number] => NUMBER
...
)
I need to replace the dash '-' to a underscore '_' within a foreach so it looks like this:
stdClass Object
(
[first_name] => NAME
[last_name] => NAME
[phone_number] => NUMBER
...
)
I found this post: PHP - How to rename an object property? which does tell me how to do it, the problem is that when I use unset() inside of the foreach it unsets all of the keys instead of just the ones I want it to.
Here's my code:
foreach ($customer as $key => $value) {
$key2 = str_replace('-', '_', $key);
$customer->$key2 = $customer->$key;
unset($customer->$key);
}
which returns an empty object:
stdClass Object
(
)
How can I unset the original keys without affecting the new ones?