Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through array of objects

Tags:

php

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

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 ?>
like image 945
Mitchell Bray Avatar asked Dec 20 '12 09:12

Mitchell Bray


People also ask

Which loop is used for array of objects?

A for loop can be used to access every element of an array. The array begins at zero, and the array property length is used to set the loop end.

Can you loop through an array?

You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.

How do you traverse an array of objects?

To iterate through an array of objects in JavaScript, you can use the forEach() method along with the for...in loop. The outer forEach() loop is used to iterate through the objects array. We then use the for...in loop to iterate through the properties of an individual object.


2 Answers

No. You will have to use an if:

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

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

like image 160
Bart Friederichs Avatar answered Sep 19 '22 15:09

Bart Friederichs


Or you can utilize PHP's array_filter function:

$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>';
}
like image 32
Andris Avatar answered Sep 21 '22 15:09

Andris