php 循环遍历对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13969469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:22:29  来源:igfitidea点击:

loop through array of objects

php

提问by Mitchell Bray

I Have an array called $pages content is as follows:

我有一个名为 $pages 的数组内容如下:

Array
(
[01-about-us] => Page Object
    (
        [_uri] => about-us
        [_menuItem] => 01
        [_visable] => 1
    )

[02-contact] => Page Object
    (
        [_uri] => contact
        [_menuItem] => 02
        [_visable] => 1
    )

[_sitemap] => Page Object
    (
        [_uri] => sitemap
        [_menuItem] => 
        [_visable] => 
    )

[home] => Page Object
    (
        [_uri] => home
        [_menuItem] => 
        [_visable] => 1
    )
)

is there an easy way to loop through and get page objects by there properties ie:

有没有一种简单的方法来循环并通过那里的属性获取页面对象,即:

<?php foreach($pages->_visible() AS $p): ?>
  <li> page </li>
<?php endforeach ?>

回答by Bart Friederichs

No. You will have to use an if:

不,您必须使用if

foreach ($pages as $page) {
    if ($page->_visible == 1) {
        echo "<li>page</li>";
    }
}

(Note also you misspelt visiblein the array, perhaps a typo?)

(还要注意你visible在数组中拼错了,也许是拼写错误?)

回答by Andris

Or you can utilize PHP's array_filterfunction:

或者你可以利用 PHP 的array_filter功能:

$pagesVisible = array_filter($pages, function($page) {
    return (bool) $page->_visible;
});

foreach ($pagesVisible as $key => $page) {
    print '<li>' . $key . '</li>';
}

Or shorthand it to:

或将其简写为:

$filter = function($page) {
    return (bool) $page->_visible;
};
foreach (array_filter($pages, $filter) as $key => $page) {
    print '<li>' . $key . '</li>';
}

回答by PhearOfRayne

You just need to loop through the pages array and inside the loop access the object properties like:

您只需要遍历 pages 数组并在循环内访问对象属性,例如:

<?php foreach($pages as $k => $p): ?>
   <?php if ($p->_visable === 1): ?>
   <li><?php echo $k; ?></li>
   <?php endif; ?>
<?php endforeach; ?>

Please note that visableis misspelled but thats how it is in your question

请注意,visable拼写错误,但这就是您的问题