Make php cake find query result to change array key using id value using Cake php itself

How to make take php find the array key of the query result to change the id value using cake php?

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

print_r($videos);

      

The array will be

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

        )

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

        )
)

      

How to change array key with id value as shown below

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

        )

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

        )
)

      

Is this possible with the php pie itself?

+3


source to share


3 answers


If you really need data in this format, you can use afterFind

to set the ids, or you can use the CakePHP Hash

/ class Set

.

Try this (since CakePHP 2.2)

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

      

Or is this for CakePHP older than 2.2



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

      

See http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html for details

If you can tell us why you need the data to be in this format, we can also offer you better ways since the data should not be changed in this way.

+8


source


No, it is not. You can change the result in afterFind (), look at book.cakephp.org, but I would just use the data as it is. I see no reason to add this additional overhead and complexity, because the ID is always available.



+1


source


In CakePHP 2.2, you can use

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

      

This will print each value with the id key.

I don't know if you can use this in 1.3, but you can try ...

+1


source







All Articles