John Davidson

Rename PHP Object property in foreach loop

0 comments
Message:


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?



My Answer:
You can achieve this by creating a new object and assigning the modified keys to it. Here's an example:

php
$newCustomer = new stdClass();

foreach ($customer as $key => $value) {
$newKey = str_replace('-', '_', $key);
$newCustomer->$newKey = $value;
}

// Now $newCustomer will have the modified keys
var_dump($newCustomer);


This way, you are creating a new object `$newCustomer` and assigning the modified keys to it without affecting the original object `$customer`.

Rate this post

4 of 5 based on 8500 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us