Welcome Guest, Not a member yet? Register   Sign In
echo dynamic, array variable
#1

[eluser]pser[/eluser]
Hi,

I have a challenge which I can find a solution for so I thought posting here might help. I use PHP and codeigniter and this is what i am trying to do.

I run a query towards a database and have the result in a array like this:

[records] => Array (
[0] => stdClass Object (
[OPID] => 5
[OPName] => Red Hat
[Created] => Oct 7 2009 1:51PM )
[1] => stdClass Object (
[OPID] => 3
[OPName] => Windows 7
[Created] => Oct 7 2009 12:00AM )
[2] => stdClass Object (
[OPID] => 4
[OPName] => Windows Server 2003
[Created] => Oct 7 2009 11:17AM )
)

I then use a foreach loop going through the array, so to typical write for example OPID I would write like this

foreach $records as $row
echo $row->OPID;
endforeach;

so far so good and this is working. But I would like to reuse the code and get it more dynamic that is I would love to write something like this:

foreach $records as $row
echo $row[$field]; // something echo $row->$field;
endforeach;

In this case the $field would contain 'OPID' which I get from a $_POST in one example and 'APID' in another, all depending of what data the user do.

So my question, is it possible to have a dynamic value in a $row field like this to get it dynamic?

In the mean time I've found a temporary solution by using reset($row) to get the first element of the array, then next($row) to get the next. I can do this because I know that the unique identifier is always first. But I would prefer to have a better solution.

The reason why I do it is because I want to reuse the code on several tables and then in the link which the user click specify which table to fetch data from. In that case I have to code less webpages, but of course it is getting a more tricky.

Any suggestions are welcome :-)

Cheers
Paal

Cheers
Paal
#2

[eluser]Ben Edmunds[/eluser]
If I understand you correctly, just use result_array() in your model instead of result().

This would give you $row['fieldname'] and then you can use $row[$field] as that is supported in PHP.
#3

[eluser]pser[/eluser]
I am sure I did try that, but.. It makes sense of what that is what I am trying to achieve. I will give it a try. Thanks for the tip.

Cheers
Paal
#4

[eluser]pser[/eluser]
Ben it is perfect, just what I wanted. When I read the code I saw that I did try $row[$data['id_field']] (you see I send the unique field in a array) but the missing link was the result_array() as $row

Thank you thank you. By the way I started with codeigniter one week ago and it's fantastic :-)

Cheers
Paal




Theme © iAndrew 2016 - Forum software by © MyBB