Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make the cake php find query result to be changed array key with id value using Cake php itself

How to make the cake php find query result array key to changed to 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 the array key with id value like below

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

        )

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

        )
)

Is it possible by cake php itself ?

like image 674
Justin John Avatar asked May 10 '26 08:05

Justin John


1 Answers

If you really need the data to be in this format, you can either use afterFind to set the IDs or you can use CakePHP's Hash/Set class.

Try this (since CakePHP 2.2)

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

Or this for CakePHP older than 2.2

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

For more details see http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html

If you might tell us why you need the data to be in this format, we can also suggest better ways for your doing since the data has not to be changed in this way.

like image 156
Jan Avatar answered May 17 '26 17:05

Jan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!