March 19, 2012

getting the value of array key in codeigniter

Question by Zoran

I have the following line in my controller:

$data['faq'] = $this->faqModel->get();  

This data print the following using the print_r

    Array
(
[faq] => Array
    (
        [0] => Array
            (
                [faqid] => 12
                [catid] => 122
                [question] => How this CMS works
                [question_en] => How this CMS works
                [answer] => How this CMS works?
                [answer_en] => How this CMS works?

                [sorder] => 2
                [visible] => 1
            )

        [1] => Array
            (
                [faqid] => 8
                [catid] => 121
                [question] => How does the design cost?
                [question_en] => How does the design cost?
                [answer] => How does the design cost?

                [answer_en] => How does the design cost?

                [sorder] => 1
                [visible] => 1
            )

    )

)

I want to use the value stored in the [catid] key, and I am trying to do something like:
$data[‘faq’][‘catid’] to get that value in the controller (I want to make another select with that value) But I am getting with this error message: Undefined index: catid

Anyone can help me to get the value of [‘catid’]???

Regards, Zoran

Answer by safarov

Its 3 dimensional array u look closely there is two elements in faq array. You must wrote something like this: $data['faq'][0]['catid'] or $data['faq'][1]['catid']

Answer by Starx

The way you are accessing the array is incorrect, you are missing the item index on the second level. The correct way to use it as you are doing would be to do

echo $data['faq'][0]['faqid']; //faqid of the first item

However, this will only show one faqid at a time, and it not so useful when you are iterating. So, a good way would be this way.

foreach($data['faq'] as $value) {
 echo $value['faqid'];
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!