phpmysqlcakephp-2.0

how to convert an cakephp mysql result into a simple array


App::import('model','User');
        $user_model = new User();
        $xxx = $user_model->find("all", array("fields"=>array("User.yyy")));
        $zzz = $user_model->find("count", array("fields" => "User.yyy"));
        $arr = array();
        for($i=0; $i<=$zzz; $i++){
                $rs = $xxx["i"]["User"]["yyy"];
                array_push($arr , $rs);
        }
        print_r($arr);

I am using the above cakephp code to get $xxx as a mysql result set.

I need to store all the values corresponding to "yyy" field in the mysql table into an arrray.

I tried printing the result set and got output like this:-

print_r($zzz)= 1646 // prints the total number of results
print_r($xxx[0]["User"]["yyy"]) = abcde   //the first element of the result set

After I run the code above, It just prints an empty array.

Can someone help me out here??


Solution

  • The problem is here:

    $xxx["i"]["User"]["yyy"]
    

    It should be:

    $xxx[$i]["User"]["yyy"]
    

    Assuming the code is located in a controller, I would write it like this:

    $this->loadModel('User');
    $arr = $this->User->find("list", array("fields"=>array("User.yyy")));
    

    find("list") should return an array indexed by id

    If you want to remove the ids, you can do this:

    $arr = array_values($arr)