2014-03-27 51 views
0

我该如何迭代这个荒谬乏味的数组?CakePHP-迭代阵列

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'数组对象中获取question_desc字段。

+0

正如我在这里看到的情况与数组的数组这里是示例http://www.w3schools.com/php/php_arrays_multi.asp也如果你知道如何迭代一个数组只需要第一次迭代后开始迭代子阵列。 – Nezir

+0

这里是示例http://stackoverflow.com/questions/10342755/cakephp-2-1-1-foreach – Nezir

+0

对不起,我可能还没有清楚...是否有一个PHP的方式做蛋糕..迭代,如Foreach很简单, – LogixMaster

回答

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以及它如何使用模型关系,蛋糕数据形式就会变得更有意义。它实际上是一个用于管理数据的强大工具,但在您需要所有这些功能之前,它似乎是简单任务的负担。

+0

Actuall由于某种原因返回一个空数组!哦,谢谢分享我的沮丧。我从字面上感觉像垃圾之间的迭代混淆。 – LogixMaster

+0

您确实已将'$ your_main_array'切换为您阵列的实际名称吗? – usumoio

+0

yes ofcourse!为什么你检查$ question_param =='question_desc'?似乎从未遇到这种情况 – LogixMaster