Reputation: 968
I have a list of categories for my videos, and with this simple foreach loop, I'm displaying all of them inside hyperlinks.
Now, what I want to do is display only some of them, based on the category ID.
Code that display all the categories:
$idx = 0;
foreach ($this->categories as $category)
{
echo "\n" . ($idx++ ? '| ' : '') . '<a href="' . KM_Helpers::getCategoryURL($category) . '">' . $category['name'] . '</a>';
}
Let's say now I want to display only the categories with the ids: 2,8,21,22. I can use $category['id'] to get the IDS.
I was thinking of having an array that contains only the ID I want to show...
$myarray = array(2, 8, 21, 22);
My question is, how can I loop in my $category array, displaying only the ID contained in the array? (Based on $category['id'] )
Upvotes: 0
Views: 172
Reputation: 95242
If the id value matches the index in the categories array, you can just loop over the ones you want:
foreach ($myarray as $id)
{
$category = $this->categories[$id];
echo "\n".($idx++ ? '| ' : '') .
'<a href="' . KM_Helpers::getCategoryURL($category) . '">' .
$category['name'] . '</a>';
}
Otherwise, you have to do a double-loop (possibly hidden by in_array
), either to check if an id is valid or to find the category with a given valid id.
Upvotes: 2
Reputation: 17885
$ids= array(2, 8, 21, 22);
$idx = 0;
foreach($this->categories as $id => $category){
if (in_array($category['id'] , $ids)) {
echo "\n".($idx++ ? '| ' : '').'<a href="'.KM_Helpers::getCategoryURL($category).'">'.$category['name'].'</a>';
}
}
Upvotes: 1
Reputation: 26380
Not a problem. Add in some simple logic to test if the id is on your list of "approved" ids:
$idx = 0;
$myarray = array(2, 8, 21, 22);
foreach($this->categories as $category)
{
if(in_array($category['id'], $myarray)
{
echo "\n".($idx++ ? '| ' : '').'<a href="'.KM_Helpers::getCategoryURL($category).'">'.$category['name'].'</a>';
}
}
This tests the $category['id'] in each iteration of the loop and if it's in your array of ids, you echo the link. Otherwise the category item is ignored and the loop moves on.
Upvotes: 1
Reputation: 219804
$idx = 0;
$myarray = array(2, 8, 21, 22);
foreach($this->categories as $category)
{
if (!in_array($category['id'], $myarray)) {
continue; // skip it if the id isn't in your array of accceptable IDs
}
echo "\n".($idx++ ? '| ' : '').'<a href="'.KM_Helpers::getCategoryURL($category).'">'.$category['name'].'</a>';
}
Upvotes: 1