0

如果我在会话中有以下数组,我能否在每个 [cat] 中获取项目位置编号:

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [cat] => 1
            [que] => Description here.
        )

    [1] => stdClass Object
        (
            [id] => 2
            [cat] => 1
            [que] => Description here.
        )

    [2] => stdClass Object
        (
            [id] => 3
            [cat] => 1
            [que] => Description here.
        )
)

例如,下面将给我第二个描述,但我如何得到它在 [cat] == 1 中的位置 #2(共 3 个):

$item = $_SESSION['questions'][2]->que;

实际的数组要大得多,并且有超过 1 个 [cat]。我试图得到的计数是每个这样的群体。

4

3 回答 3

0
    foreach($_SESSION['questions'] as $key=>$val)
    {
      if($val->id == 3)
      echo $key;
    }

//or

    foreach($_SESSION['questions'] as $key=>$val)
    {
      if($val->que == "Description here.")
      echo $key;
    }

//do what ever you want
于 2012-11-14T14:01:29.253 回答
0

我确定您正在寻找一种更原生的方式,但更糟糕的情况是,您可以添加另一个元素来保存索引值。

于 2012-11-14T13:53:36.297 回答
0

通过在数组的开头添加一个虚拟条目:

array_unshift($_SESSION['questions'], array());
$item = $_SESSION['questions'][2]->que;
于 2012-11-14T13:55:43.517 回答