数组中的任意元素(值)为数组的键

时间:2013-11-12 01:09:43

标签: php cakephp

所以,我有一个看起来像这样的数组:

$grades =
Array(

    [0] => Array ( [Grade] => Array ( [id] => 0 [name] => Kindegarten ) ) 
    [1] => Array ( [Grade] => Array ( [id] => 1 [name] => First ) ) 
    [2] => Array ( [Grade] => Array ( [id] => 2 [name] => Second ) ) 
    [3] => Array ( [Grade] => Array ( [id] => 3 [name] => Third ) ) 
    [4] => Array ( [Grade] => Array ( [id] => 4 [name] => Fourth ) ) 
    [5] => Array ( [Grade] => Array ( [id] => 5 [name] => Fifth ) ) 

    )//End array 

我想知道有没有办法随心所欲地选择一把钥匙(前0-5)? CakePHP像这样返回我表中的项目,我不明白如何使用选项打印Form helper。

echo $this->Form->input('grade_selection', 
        array('type' => 'radio', 'options' => array($grades[?]['Grade']['id'] => $grades[?]['Grade']['name'])));

?是如何让它在选项中更改,以便我可以获得数组中的每个项目?

class GradesController extends AppController {
    public function index(){
        //Gets all the rows in the grade table and stores it into a variable called grade. 
        //$grades = $this->Grade->find('all'); 
        $grades = $this->Grade->getGrades();

        //Returns the $grades variable when it is requested. 
        if($this->request->is('requested')){
            return $grades;
        }

        //Sends the $grades variable to the view file. The string 'grades' is the name of the variable that the Grades View file will have the same setup as the $grades.
        $this->set('grades', $grades);
    }
}

1 个答案:

答案 0 :(得分:0)

  

我想知道有没有办法随心所欲地选择一把钥匙(前0-5)?

是的,php,不是CakePHP

$keys = array_keys($grades);
$foo = $keys[rand(0, count($keys) - 1)]

现在,我不认为这就是你所需要的。我看到你正在使用一个单选按钮,你想在单选按钮中显示什么?

修改

假设此数据来自名为“Grade”的模型,您可以在crontroller中执行此操作

$grades = $this->Grade->find('list');
$this->set(compact('grades'));

然后,在您看来:

echo $this->Form->input('grade_selection', array('options' => $grades));