Build a string from a resultset array

Sometimes it’s very handy to be able to quickly build a string from CakePHP’s resultset array. For example you want to build a string of ID’s to be used with the “IN” condition in your DB (such as Profile.id IN(1,2,3,4)… ).

Let’s say we did a find(‘all’… and got an array similar to this one:

Array
(
    [0] => Array
        (
            [Account] => Array
                (
                    [id] => 23
                )

        )

    [1] => Array
        (
            [Account] => Array
                (
                    [id] => 24
                )

        )

    [2] => Array
        (
            [Account] => Array
                (
                    [id] => 25
                )

        )

)

Our goal is to extract the ID’s from the above array into 23,24,25.

Here we go (assuming that $acctIds is our resultset array from above):

$stringOfIds = implode(',', Set::extract($acctIds, '{n}.Account.id'));

Cake’s Set class is full of magic and here we are using the extract method to get just the values we are interested in, then we implode the resulting array with a comma.

Note the {n} above. It simply represents a numeric key and therefore allows us to easily follow the path to the desired value in the array.

 

Related Posts

%d bloggers like this: