开发者

Array manipulation to create a dropdown box cakephp

this is my problem i,ve to create a dropdown list box from a table states('id','state_name') which is not my default model( which has many fields one of the field is 'state' in which i store states(开发者_开发技巧'id') . so i used loadModel to populate the drop down box. in my controller i used

$this->loadModel('State');
$this->set('states',$this->State->find('all'));

in the view side

$form->select('State_id',$states);

in the output the table name, the id and name are displaying.

when i printed $states using pr(); what i got was

Array
(
    [0] => Array
        (
            [State] => Array
                (
                    [id] => 1
                    [state_name] => state1
               )

        )

    [1] => Array
        (
            [State] => Array
                (
                    [id] => 2
                    [state_name] => state2
                )

        )

and so on

how to create an array like array(1=>state1, 2=>state2) from the above array or is there any other way to create a dropdown listbox

kindly help


This is the way:

$fields = array('id','state_name');
$states = $this->State->find('list',array('fields'=>$fields));
$this->set(compact('states'));

or in one line:

$this->set('states',$this->State->find('list',array('fields'=>array('id','state_name'))));


The below code will create the array you wanted from the original array

$newstates = array();

foreach($states as $state) {
    $state = $state['State']
    $newstates[$state['id']] = $state['state_name'];
}

print_r($newstates);

Result:

Array
(
    [1] => state1
    [2] => state2
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜