Question

I am currently trying to figure out how to save a indexed array to a field in my database. That said, I know an array can't be saved to a database, but you can serialize it or implode it and then save. Im not sure which one I should be using though. I don't want a collection of items to be saved in just one cell. I need the list of items to be saved one by one in the column. So my question is do I need to be using the serialize method, implode or something else? Here is a glimpse of my code and the array I am trying to save.

 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) {
            $all[] = $id['Policy']['id'];




        }
        return $all;
}


 Array
(
[0] => 5202834f-111c-4a76-8b33-1ed8ae78509d
[1] => 5202834f-2ba8-4957-91db-1ed8ae78509d
[2] => 5202834f-356c-49a1-beeb-1ed8ae78509d
[3] => 5202834f-3b40-453f-a491-1ed8ae78509d
Was it helpful?

Solution

It depends.

This is probably the best answer to give you.

Do whatever you like, as long as it doesn't magically corrupt the data between write and read.

Lemme take a moment to explore a few options on your behalf.

  • var_export() - might not be the best idea, securitywise
  • serialize() - seems straightforward
  • implode() - seems straightforward
  • json_encode() - seems straightforward

There are probably other, more obscure, options available. You could even build up complex data sets with XML, if you like.

Alternatively, why not normalize the schema and add a new table to present that collections of array-data ? Normalization tends to save your bacon in the future.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top