Welcome Guest, Not a member yet? Register   Sign In
DB Row Results and Multidimensional Array Logic
#1

[eluser]underskor[/eluser]
I am retrieving X rows from the DB in a model, and want to refer to the fields of each row. I think the best way to do it is through multidimensional arrays, but I can figure out how to do it.

Code:
$this->db->select('field0, field1, field2, field3, field4');
$this->db->from('table');
$this->db->order_by('field0', 'desc');
$this->db->limit(5);
$query = $this->db->get();
        
$row_count = $query->num_rows;
for($i=0; $i<=$row_count; $i++)
{
    //This is about where I got lost
    foreach ($query->result_array() as $row[$i])
    {
        return $row;
    }
}

I want to be able to do the following:
Code:
echo $row[0]['field0'];
echo $row[0]['field1'];
echo $row[0]['field2'];
[..]
echo $row[1]['field0'];
echo $row[1]['field1'];
echo $row[1]['field2'];
[..]
and so on

It's probably something simple, but I've had a read over the documentation and can't see any examples/functions which look to be of any help.

Thanks
#2

[eluser]simonmaddox[/eluser]
I think I know what you're after. Try this:

Code:
foreach ($query->result_array() as $key=>$row[$i])
    {
        // you can now access the field name by using $key
    }
#3

[eluser]underskor[/eluser]
Thanks for your reply.

I'm not sure if I understood what you said correctly (using $key[row][field]), but I fiddled around and got it working in the end.

Code:
print_r($key); //Gives nothing

print_r($row); //Gives..

/*
Array
(
    [0] => Array
        (
            [field0] => 'value'
            [field1] => 'value'
        )

    [1] => Array
        (
            [field0] => 'value'
            [field1] => 'value'
        )

    [2] => Array
        (
            [field0] => 'value'
            [field1] => 'value'
        )
)*/

I feel that my implementation of it is a bit strange though. Can anyone offer some advice?
Code:
function func()
{
    [..db..]

    foreach ($query->result_array() as $key=>$row[])
    {
    }
    return $row;
}

$row = func();

echo $row[0]['field_name'];
#4

[eluser]Michael Wales[/eluser]
result_array() will return a multidimensional without you doing anything.

Code:
function get_all() {
  $query = $this->db->get('users');
  if ($query->num_rows() > 0) {
    return $query->result_array();
  }
  return FALSE;
}

Code:
$users = $this->user->get_all();
echo '<pre>';
print_r($users);
echo '</pre>';

/* Output:
$users = array(
    [0] = array(
        'username'  => 'walesmd',
        'real_name' => 'Michael Wales'
    ),
    [1] = array(
       'username' => 'dallard',
       'real_name' => 'Derek Allard'
    )
)*/

Even if it only returned one result, it would be a multidimensional array ($users[0]).




Theme © iAndrew 2016 - Forum software by © MyBB