首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >in_array没有按照我所理解的那样工作

in_array没有按照我所理解的那样工作
EN

Stack Overflow用户
提问于 2013-12-30 00:03:45
回答 2查看 129关注 0票数 0

我有这样的代码:

代码语言:javascript
复制
<ul style="list-style-type:none;">
<?php foreach ($rawmenuitems as $rawmenuitem) 
    { 
    if (in_array($rawmenuitem->note, $completedmenuitems))
    { ?>
        <li>
        <span style="color:#666666; "><?php echo ($rawmenuitem->title); ?></span>
        </li>
<?php   }
    else
    { ?>
        <li>
        <?php echo ('<a href =' . $rawmenuitem->link . '&amp;Itemid=' . $rawmenuitem->id . '">' . $rawmenuitem->title . '</a>'); ?>
        </li>
<?php   }
}?>
</ul>

这些数组包括:

代码语言:javascript
复制
$rawmenuitems ( 
[0] => stdClass Object ( [link] => index.php?option=com_breezingforms&view=form [id] => 1378 [title] => 334 Basic Information [note] => 5 ) 
[1] => stdClass Object ( [link] => index.php?option=com_breezingforms&view=form [id] => 1381 [title] => 334 Drug Testing [note] => 17 ) 
[2] => stdClass Object ( [link] => index.php?option=com_breezingforms&view=form [id] => 1380 [title] => 334 Emergency Treatment [note] => 15 ) 
[3] => stdClass Object ( [link] => index.php?option=com_breezingforms&view=form [id] => 1379 [title] => 334 Extracurricular [note] => 7 ) 
[4] => stdClass Object ( [link] => index.php?option=com_breezingforms&view=form [id] => 1377 [title] => 334 Florida Concussion [note] => 12 ) 
[5] => stdClass Object ( [link] => index.php?option=com_breezingforms&view=form [id] => 1376 [title] => 334 Florida Consent [note] => 14 )
) 

代码语言:javascript
复制
$completedmenuitems ( 
[0] => stdClass Object ( [id] => 1377 [note] => 12 ) 
[1] => stdClass Object ( [id] => 1376 [note] => 14 ) 
)

但代码的输出只有六个链接,而不考虑条件的结果。有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2013-12-30 00:08:46

这些是对象的数组-所以在数组$completedmenuitems中没有对象"5“。存在属性note = 5的对象。

你必须从数组中的对象中提取note到其他数组。

代码语言:javascript
复制
$completedmenuitems_notes = array_map(
    create_function(
        '$object', 
        'return $object->note;'
    ), 
    $completedmenuitems
);
票数 3
EN

Stack Overflow用户

发布于 2013-12-30 00:08:31

$rawmenuitem->note是一个整数,而$completedmenuitems是一个包含名为note的属性的对象数组。因此,in_array()将整数与对象进行比较。

这个问题有多种解决方案。一种是使用他自己的函数:

代码语言:javascript
复制
function isCompletedItem($completedItems, $note) {
  foreach ($completedItems => $items) {
    if ($items->note == $note) {
      return true;
    }
  }
  return false;
}

if (in_array($completedmenuitems, $rawmenuitem->note))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20827085

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档