根据存储在键内的值从二维数组中选择值?

时间:2012-04-25 07:10:56

标签: php arrays multidimensional-array extract

嗨朋友我正在进行调查我需要从存储在其中的数组中提取数组

如何做到这一点我希望根据问题ID提取答案数组,例如13。

我有问题ID。答案数组与问题相关联。

。如何根据问题id的值从主数组中提取问题数组和答案数组,例如13

现在如果我需要具有问题ID的数组及其关联的id如何从我的数组结构中执行它?

我的代码就像这样

Array
(
    [0] => Array
        (
            [que_info] => Array
                (
                    [question_id] => 13

                    [description] => Overall Customer Satisfaction.




                )

            [answers] => Array
                (
                    [0] => Array
                        (
                            [answer_id] => 45

                            [answer_text] => Very dissatisfied

                        )


                )

        )

    [1] => Array
        (
            [que_info] => Array
                (
                    [question_id] => 14

                    [description] => Progress (often referred to as Task Resolution or similar)


                )

            [answers] => Array
                (
                    [0] => Array
                        (
                            [answer_id] => 52

                            [answer_text] => None

                        )

                    [1] => Array
                        (
                            [answer_id] => 53

                            [answer_text] => Very little

                        )


                        )



                )

        )

任何帮助将不胜感激:)

2 个答案:

答案 0 :(得分:2)

function find_question($array, $id) {
    foreach ($array as $arr)
    {
        if ($arr['que_info']['question_id'] == $id)
            return $arr;
    }
}

var_dump(find_question($array, 13));
var_dump(find_question($array, 14));

答案 1 :(得分:2)

首先,这不是2D数组,而是数组树。对于每个数组[x],2D数组总是有一个元素数组[x] [y],而对于任何数组[x] [y] [z]都没有。

使用foreach迭代数组,并在找到id为与question_id对应的元素时返回答案列表。

示例:

  foreach($questions as $question) {
    if($question['que_info']['question_id'] === $questionId)
      return $question['answers'];
  }