Question

I am trying to loop through a multi-dimensional array and stored the results in a variable to I can return the results and save them. That said, I have looked around on the SUPER INFORMATION HIGHWAY......and I can not find too much that can help me with my problem. This is what I have tried so far.

public function findPolicyIds($coverageId = null) {
    $policyid = $this->Policy->find('all', array(
        'recursive' => -1,
        'conditions' => array('Policy.coverage_id' => $coverageId),
        'fields' => array('Policy.id')));

        foreach($policyid as $id) {

        }
        return $id;
}

When I run my script I only get one result. If I run the script without the foreach statement and I return policyid I get the following results.

Array
(
[0] => Array
    (
        [Policy] => Array
            (
                [id] => 520015be-2bc8-48ca-b5d1-63ebae78509d
            )

    )

[1] => Array
    (
        [Policy] => Array
            (
                [id] => 520015be-48bc-496d-b8f8-63ebae78509d
            )

    )

[2] => Array
    (
        [Policy] => Array
            (
                [id] => 520015be-5a08-47b6-9e97-63ebae78509d
            )

    )

I just want to loop through these id's so I can save them and return them to another method.

Was it helpful?

Solution

The foreach loop is assigning each element of the policyid array to the $id variable in turn. It is not being reset so much as re-assigned (to each element of the array you are iterating over).

In order to return an array of only the ids, you will need to collect them and then return the new collection:

public function findPolicyIds($coverageId = null) {

    ....

    $all = array();
    foreach($policyid as $id) {
        // here we are collecting only the ID value...
        $all[] = $id['Policy']['id'];
    }

    return $all;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top