【问题标题】:Make the cake php find query result to be changed array key with id value using Cake php itself使用 Cake php 本身使 cake php 查找查询结果更改为 id 值的数组键
【发布时间】:2012-03-30 15:29:14
【问题描述】:

如何让 cake php 使用 cake php 查找查询结果数组 key 变为 id 值?

$videos = $this->Video->find('all');

print_r($videos);

数组将是

Array
(
    [0] => Array
        (
            [Video] => Array
                (
                    [id] => 6
                )

        )

    [1] => Array
        (
            [Video] => Array
                (
                    [id] => 8
                )

        )
)

如何用下面的 id 值更改数组键

Array
(
    [6] => Array
        (
            [Video] => Array
                (
                    [id] => 6
                )

        )

    [8] => Array
        (
            [Video] => Array
                (
                    [id] => 8
                )

        )
)

蛋糕php本身可以吗?

【问题讨论】:

    标签: cakephp cakephp-1.3


    【解决方案1】:

    如果您确实需要这种格式的数据,您可以使用afterFind 来设置ID,也可以使用CakePHP 的Hash/Set 类。

    试试这个(从 CakePHP 2.2 开始)

    $videos = $this->Video->find('all');
    $videos = Hash::combine($videos, '{n}.Video.id', '{n}');
    debug($videos);
    

    或者对于早于 2.2 的 CakePHP 来说这个

    $videos = $this->Video->find('all');
    $videos = Set::combine($videos, '{n}.Video.id', '{n}');
    debug($videos);
    

    更多详情见http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html

    如果您可以告诉我们为什么您需要采用这种格式的数据,我们还可以为您提供更好的方法,因为不必以这种方式更改数据。

    【讨论】:

      【解决方案2】:

      不,不是。您可以在 afterFind() 中更改结果,查找 book.cakephp.org,但我会直接使用数据。我认为没有任何理由增加这种额外的开销和复杂性,因为 id 无论如何都是可用的。

      【讨论】:

        【解决方案3】:

        在 CakePHP 2.2 中你可以使用

        $videos = $this->Video->find('list');
        pr($videos);
        

        这将打印以 id 作为键的每个值。

        我不知道你是否可以在 1.3 中使用它,但你可以尝试...

        【讨论】:

          猜你喜欢
          • 2014-03-19
          • 1970-01-01
          • 1970-01-01
          • 2012-03-16
          • 2020-02-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多