Welcome Guest, Not a member yet? Register   Sign In
Turning a string into an array within result object?
#1

[eluser]Unknown[/eluser]
I'm working with a database that stores one field as a string, but it's really a | separated list.

When working with this I can convert those individually to arrays, but that moves it outside of the result object and disassociates it from the other data in the database.

I'm trying to figure out the best/recommended way to embed an array into the result object (or a copy of the result) but I'm not very speedy with figuring out how to manipulate the results of a db call and how best to package it all back together (coming from JS where objects vs arrays are the same)

This is the function I'm working on:

Code:
function get_answers($upid, $sid = NULL) {
  if (isset($sid)){
   $this->db->join('question', 'question.qid = answer.a_qid_fk', 'left');
   $this->db->where('q_sid_fk', $sid);
  }
     $results = $this->db->get_where('answer', array('a_upid_fk' => $upid))->result();

     foreach ($results as $row) {
      $answer_array = explode('|', $row->answer, -1);
      // foreach ($answer_array as $instance) {
      //   $result[] = $instance;
      // }
     }


  // foreach ($result->answer as $ans) {
  //  $result->answers = explode( '|', $ans, -1 );
  // }

     return $results;
}

I'm getting results like:
Code:
array (
  0 =>
  stdClass::__set_state(array(
     'aid' => '742',
     'a_upid_fk' => '231',
     'answer' => '4555|||',
     'a_qid_fk' => '70',
     'created' => '2012-03-20 15:35:38',
     'last_modified' => '2012-03-20 15:36:11',
     'revision' => '1',
  )),

But I want them to look like this:
Code:
array (
  0 =>
  stdClass::__set_state(array(
     'aid' => '742',
     'a_upid_fk' => '231',
     'answer' => array (
        0=> '4555',
        1=> '',
        2=> ''),
     'a_qid_fk' => '70',
     'created' => '2012-03-20 15:35:38',
     'last_modified' => '2012-03-20 15:36:11',
     'revision' => '1',
  )),

It doesn't *have* to be an object the same way, but I figure I'd want it to be that way for consistency
#2

[eluser]Aken[/eluser]
Try passing the results array row by reference, then modify it directly.

Code:
foreach ($results as &$row)
{
    $row->answer = explode('|', $row->answer, -1);
}




Theme © iAndrew 2016 - Forum software by © MyBB