我不确定我是否正确地提出了这个问题,但基本上我从WordPress得到以下数组结果我试图处理:
Array
(
[0] => WP_User Object
(
[data] => stdClass Object
(
[ID] => 3
[user_login] => Jean Gomes
[user_pass] => $P$BvW6LK9/blGKLuSj.9spNPW3.v104..
[user_nicename] => jean-gomes
[user_email] => jean.gomes@dpa.dev
[user_url] =>
[user_registered] => 2014-08-28 10:56:39
[user_activation_key] =>
[user_status] => 0
[display_name] => Jean Gomes
)
[ID] => 3
[caps] => Array
(
[author] => 1
)
[cap_key] => dpa2335327_capabilities
[roles] => Array
(
[0] => author
)
[allcaps] => Array
(
[upload_files] => 1
[edit_posts] => 1
[edit_published_posts] => 1
[publish_posts] => 1
[read] => 1
[level_2] => 1
[level_1] => 1
[level_0] => 1
[delete_posts] => 1
[delete_published_posts] => 1
[wpseo_bulk_edit] => 1
[author] => 1
)
[filter] =>
)
[1] => WP_User Object
(
[data] => stdClass Object
(
[ID] => 4
[user_login] => Tammy Day
[user_pass] => $P$BejydpFxKDp60WruV71u0/JnJm9o.E.
[user_nicename] => tammy-day
[user_email] => tammy.day@dpa.dev
[user_url] =>
[user_registered] => 2014-08-28 10:57:23
[user_activation_key] =>
[user_status] => 0
[display_name] => Tammy Day
)
[ID] => 4
[caps] => Array
(
[author] => 1
)
等
我想使用这些结果为ID {。<}执行foreach
E.g。
foreach ( $authors as $author_id ) {
但我不知道如何访问ID。我试过了:
foreach ( $authors->ID as $author_id ) {
但显然这不起作用,因为之前有一个数字,是否有相当于:
foreach ( $authors['X']->ID as $author_id ) {
我可以用吗?
对不起我知道这可能是一个愚蠢的问题,但我很困惑。我知道我可能不得不在foreach中做一个foreach,但我根本无法解决语法问题。
答案 0 :(得分:1)
你不能尝试这个而不是foreach:
$i=0;
while ($i<count($authors)){
$author_id = $authors[$i]['data']['id'];
//Do whatever you want here.
$i=$i+1;
}
答案 1 :(得分:1)
如转储所述,数组元素是WP_User的实例。您可以使用以下循环来获取ID:
foreach ($authors as $User) {
$author_id = $User->ID;
// Act
}
有关WP_User类的参考,请参阅http://codex.wordpress.org/Class_Reference/WP_User
答案 2 :(得分:1)
foreach (array_expression as $value)
在每次迭代中,当前元素的值被赋值为$ value,内部数组指针被提前一个(因此在下一次迭代中,您将查看下一个元素)。
阅读this文档页面,详细了解foreach
循环:
在您的情况下,$ value将指向WP_User Object
的实例。要访问用户的ID,只需阅读对象的属性ID
foreach ( $authors as $author ) {
$author_id = $author->ID;
}