cakephp中find('list')的使用

运用一、快速实现下拉菜单

控制器中,使用find('list')返回的是键值对的数组,键名是array的第一个参数id,键值就是第二个参数content。

    public function list_select(){
        //查询键值对
        $list = $this->Post->find('list',array('fields' => array('Post.id','Post.content')));
        //var_export($list);
        $this->set('options',$list);
    }

 $list的内容类似

array ( 1 => 'new_content', 2 => 'content2', 3 => 'new_content', 4 => 'c4', 5 => 'w', )

View中,$list的格式恰恰满足$options选项的要求

<?php
echo $this->Form->input('', array(
          'name' => 's',
          'options' => $options,
          'empty' => '(choose one)'
     ));
?>

生成结果是个下拉列表,内容就是之前的键值对

运用二、将查询的结果集放到一个数组中

有表property_type,结构如图

$arr_ids = explode(',', '1,2,3');
$result = $this->PropertyType->find('all', array(
    'fields'=>array('name'),
    'conditions'=>array('id' => $arr_ids)
    )
);

使用find('all')得到的结果,三条记录是三个数组

Array
(
    [0] => Array
        (
            [PropertyType] => Array
                (
                    [name] => House
                )

        )

    [1] => Array
        (
            [PropertyType] => Array
                (
                    [name] => Unit
                )

        )

    [2] => Array
        (
            [PropertyType] => Array
                (
                    [name] => Townhouse
                )

        )

)

改为find('list')

$arr_ids = explode(',', '1,2,3');
$result = $this->PropertyType->find('list', array(
    'fields'=>array('name'),
    'conditions'=>array('id' => $arr_ids)
    )
);

得到的所有结果在一个数组中,结构干净许多

Array
(
    [1] => House
    [2] => Unit
    [3] => Townhouse
)

再将数组转为字符串 implode(',',$result);

原文地址:https://www.cnblogs.com/mafeifan/p/3266607.html