变量 $results
上的我的 var_dump
显示类似这样的内容
array (size=11)
0 =>
object(stdClass)[69]
public 'Tables_in_database-name-here' => string 'wp_commentmeta' (length=14)
1 =>
object(stdClass)[68]
public 'Tables_in_database-name-here' => string 'wp_comments' (length=11)
2 =>
object(stdClass)[67]
public 'Tables_in_database-name-here' => string 'wp_links' (length=8)
...
10 =>
object(stdClass)[59]
public 'Tables_in_database-name-here' => string 'wp_users' (length=8)
我希望能够从上述结构中提取表名,并以逗号分隔的形式列出它们,如下所示;
`wp_commentmeta,wp_comments,wp_links....,wp_users`
不过,我的大脑突然僵住了,不知道如何从该结构中提取这些数据。
我尝试了很多选项,你可以通过下面的代码来遵循它 - 每个选项都会以错误结束!
foreach ($results as $current_item):
/*
* $current_item is something like this:
*
* object(stdClass)[69]
public 'Tables_in_database-name-here' => string 'wp_commentmeta' (length=14)
*/
# echo $current_item;
# fires an error as "Catchable fatal error: Object of class stdClass could not be converted to string"
# echo $current_item[1];
# fires an error as "Cannot use object of type stdClass as array in..."
# echo array_values($current_item);
# fires an error as "array_values() expects parameter 1 to be array, object given in .."
# echo $current_item['Tables_in_database-name-here'];
#fires an error as "Cannot use object of type stdClass as array in "
how do you get that darn thing? :)
endforeach;
最佳答案
您的主要问题是属性名称 Tables_in_database-name-here
无法通过通常的 $obj->propertyName
方式表示。 PHP 允许您通过 $obj->{'invalid-variable-name-but-ok-as-a-property'}
使用字符串属性名称。
我只需通过 implode()
和 array_map()
构造字符串,例如
$string = implode(',', array_map(function($result) {
return $result->{'Tables_in_database-name-here'};
}, $results));
关于属性名称,您还可以将 stdclass
对象强制转换为数组。例如...
$associativeArray = (array) $result;
// array(1) { ["Tables_in_database-name-here"] => string(14) "wp_commentmeta" }
$indexedArray = array_values($associativeArray);
// array(1) { [0] => string(14) "wp_commentmeta" }
关于php - 从 stdClass 对象中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24728284/