我从早上开始整整一天都在没有解决方案的情况下处理这个问题。
我有这些数据来自数据库。我使用PHP PDO连接。
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 ) )
我想重命名对象中的键,而不是将testing_id重命名为id,将testing_name重命名为name等。
我已经写了如下所示的函数数量
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;
}
和这个
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;
}
在所有情况下,我只获得一个对象结果,而不是重命名整个对象
stdClass Object ( [id] => 2 [name] => please [location] => be done to me )
如何重命名对象中的每个索引并重命名完整对象?请帮忙
我需要输出像这样
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 ) )
我在这里搜索过没有任何类似的解决方案
答案 0 :(得分:1)
您正在覆盖foreach中的对象值:
$object->$new_key = $value;
$object
始终是同一个变量,尝试这样的事情:
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;
}
这将为您提供一系列对象。