I have spent the whole day since morning to handle this without the solution.
I have these data comes from database. I use PHP PDO connection.
Array (
[0] => stdClass Object ( [testing_id] => 4 [testing_name] => please [testing_location] => kjnkdsnkdnskjndkjsndjknskdnsk )
[1] => stdClass Object ( [testing_id] => 3 [testing_name] => please [testing_location] => jknds ndns )
[2] => stdClass Object ( [testing_id] => 2 [testing_name] => please [testing_location] => be done to me ) )
I want to rename keys in objects instead of testing_id to be just id, testing_name to be name etc.
I have write number of functions like this below
function remove_keys($arr, $table) {
$object = new stdClass();
foreach ($arr as $key => $val) {
$x = (array) $val;
foreach ($x as $key2 => $value) {
$new_key = str_replace($table, '', $key2);
$object->$new_key = $value;
}
}
return $object;
}
and this
function replaceKey(&$array,$table) {
$x = array();
foreach($array as $k => $v){
$new_key = str_replace($table, '', $k);
array_push($x, $new_key);
}
$array = array_combine($x, $array);
return $array;
}
In all cases, I get only one object result instead of renaming the whole object
stdClass Object ( [id] => 2 [name] => please [location] => be done to me )
How can I rename each index in object and get the full object renamed? Any help please
I need the output to be like this
Array (
[0] => stdClass Object ( [id] => 4 [name] => please [location] => kjnkdsnkdnskjndkjsndjknskdnsk )
[1] => stdClass Object ( [id] => 3 [name] => please [location] => jknds ndns )
[2] => stdClass Object ( [id] => 2 [name] => please [location] => be done to me ) )
I have searched here without any similar solution
You are overwriting the object value in the foreach:
$object->$new_key = $value;
$object
is always the same variable, try something like this:
function remove_keys($arr, $table) {
$temp_array = array();
foreach ($arr as $key => $val) {
$object = new stdClass();
$x = (array) $val;
foreach ($x as $key2 => $value) {
$new_key = str_replace($table, '', $key2);
$object->$new_key = $value;
}
$temp_array[] = $object;
}
return $temp_array;
}
This will give you back an array of objects.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.