我试图从一个充满新闻项及其参数的数组中获取特定值。
我的阵列有25个项目,来自6个不同的类别,我只需要获取类别名称但不能获得25次。如果我不完全清楚,那就说出来
这是print_r($this->primary)
:
Array(
[0] => stdClass Object
(
[title]=> Title 1
[categoryname]=> Cat1
[categoryid]=> 2
)
[1] => stdClass Object
(
[title]=> Title 2
[categoryname]=> Cat1
[categoryid]=> 2
)
[2] => stdClass Object
(
[title]=> Title 3
[categoryname]=> Cat2
[categoryid]=> 3
)
[3] => stdClass Object
(
[title]=> Title 4
[categoryname]=> Cat2
[categoryid]=> 3
)
)
我的循环是:
for each ($getids->categories as $key=>$mycategory)
{
echo ' <h2> CAT NAME SHOULD GO HERE</h2> ';
for each ($this->primary as $key=>$item){
if ($mycategory == $item->categoryid){
echo $item->title;
}
}
}
问题是我需要在 开始for each
之前使用类别名称 。愚蠢的是$getids->categories
除了类别ID之外没有给我任何其他东西。我无法使用$this->primary[0]
获取它,因为这些项目不是按类别分组,而是如上所示只是滚动到数组中,
任何帮助表示赞赏。谢谢!
编辑:这是print_r($getids->categories)
:
Array
(
[0] => 11
[1] => 14
[2] => 12
[3] => 13
[4] => 15
[5] => 21
[6] => 20
[7] => 29
)
答案 0 :(得分:1)
使用当前设置,除了将categoryName调用25次外,您别无选择。如果你想避免这样做,我会考虑重构你的代码,以便$ this-&gt; primary不会充满所有内容。假设您从模型中获取这些值,您可以将模型函数更改为按类别名称限制。
foreach($categoryNames as $categoryName) {
$this->primaryArray[$categoryName] = Foo.getByCategoryName($categoryName);
}
foreach($this->primaryArray as $categoryName => $primary) {
echo '<h2>' . $categoryName . '</h2>';
foreach($primary as $key=>$item){
echo $item->title;
}
}
修改
按类别排序(尽管您仍会拨打25次):
$primaryArray = array();
// sort array by category
foreach($this->primary as $value) {
$primaryArray[$value->categoryName] = $value;
}
foreach($primaryArray as $categoryName => $primary) {
echo '<h2>' . $categoryName . '</h2>';
foreach($primary as $key=>$item){
echo $item->title;
}
}
答案 1 :(得分:1)
假设您想要保留$ getids-&gt;类别返回的类别顺序,您可以尝试这样的事情:
//Group items by category.
$itemsByCategory = array()
foreach($this->primary as $item) {
if ( !isset($itemsByCategory[$item->categoryid] ) {
$itemsByCategory[$item->categoryid] = array();
}
$itemsByCategory[$item->categoryid][] = $item;
}
//Print items in each category.
foreach($getids->categories as $mycategory):
if ( isset($itemsByCategory[$mycategory]) ) {
$categoryName = $itemsByCategory[$mycategory][0]->categoryname;
echo '<h2>', $categoryName ,'</h2>';
foreach($$temsByCategory[$mycategory] as $key=>$item){
echo $item->title;
}
}
endforeach;
答案 2 :(得分:1)
看看这是否适合您,
foreach($this->primary as $key=>$item)
{
$headingPrinted = false;
foreach($getids->categories as $key=>$catID) {
if($catID == $item->categoryid){
if (!$headingPrinted) {
echo '<h2>'.$item->categoryname.'</h2>';
$headingPrinted = true;
}
echo $item->title;
}
}
}