arrays - 在 CakePHP 3.x Controller 中获取一列

标签 arrays cakephp cakephp-3.0

如何用sql获取一列并将其转换为数组并在 Controller 中使用?

$allid = $this ->TabelName
            ->find('list',array(
                'fields' => array('id'),
                'conditions' => array(
                    'User_id' => '1'
                )
            ));
        $this->set(compact('allid'));



        $data = $allid->toArray();
        echo $data;

我需要的是在 Controller 中有这个 $data=array("1","2","3"); 这都是来自 TableName 的 id。有人可以告诉我该怎么做吗?

最佳答案

在蛋糕3中你可以使用集合

$allid = $this ->TableName->find()
    ->select(['id'])
    ->where(['User_id' => '1']);

$allid = $allid
    ->extract('id')
    ->toArray();

参见手册here

代替 extract - 如果您需要获取表示数组的字符串 - 您可以使用map和reduce()

$allid = $allid
   ->map(function ($value, $key) {
        return '"'.$value->id.'"';
    })
    ->reduce(function ($accumulated, $value) {
        return $accumulated.", " .$value;
    });

关于arrays - 在 CakePHP 3.x Controller 中获取一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48684664/

相关文章:

unit-testing - CakePHP 3 : Set current time for unit testing

mysql - CakePHP 3.0 - 如何记录不使用执行的事务上的错误?

c - 为什么在 fftw 中按行声明复数数组?

php循环遍历多个数组

cakephp:如何访问另一个没有关联的模型

cakephp - 不要在 CakePHP 中显示某些记录

php - 找不到 CakePHP 3.0 bin/cake 命令

javascript - 对象中的最高值,用键显示,javascript

javascript - 遍历数组数组

php - Cookie Lifetime 无法按预期工作