CakePHP-迭代数组

时间:2014-03-27 19:40:34

标签: cakephp multidimensional-array

如何对这个荒谬乏味的数组进行迭代?

array (size=6)
  0 => 
    array (size=1)
      'Question' => 
        array (size=2)
          'id' => string 'q_1' (length=3)
          'question_desc' => string 'Is this correct?)' (length=15)
  1 => 
    array (size=1)
      'Question' => 
        array (size=2)
          'id' => string 'q_10' (length=4)
          'question_desc' => string 'Do you weigh less than 45 kilograms OR more than 160 kilograms.' (length=63)

这是来自会话数据的var_dump!我需要从每个question_desc数组对象中获取'Question'字段。

1 个答案:

答案 0 :(得分:2)

这个数组的目的是结构,但我理解你在rtfm-ed之前分享它的挫败感!

$flattened_data = array();

foreach($your_main_array as $question)
{
    foreach($question['Question'] as $question_param)
    {
        if($question_param == 'question_desc')
        {
            $flattened_data[] = $question_param;

            // if you want to be really cool you can do this instead
            // this will list the array with the question id as the key.
            //  $flattened_data[$question[id]] = $question_param;           
        }
    }
}

// now flattened data has only what you require
return $flattened_data;

一旦你理解了它的ORM以及它如何使用模型关系,蛋糕数据形式会更有意义。它实际上是一个管理数据的强大工具,但在您需要所有这些功能之前,它看起来似乎是简单任务的障碍。