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 ?>
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.
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.
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.
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?)
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>';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With