0

how to get the array data into foreach loop in php

am having the code as follows

 $years = $this->report_model->get_year();
            print_r($years);

when am printing am getting as

Array ( [0] => stdClass Object ( [financial_year] => 1972-1973 ) [1] => stdClass Object ( [financial_year] => 1973-1974 ) [2] => stdClass Object ( [financial_year] => 1974-1975 ) [3] => stdClass Object ( [financial_year] => 1975-1976 ) [4] => stdClass Object ( [financial_year] => 1976-1977 ) [5] => stdClass Object ( [financial_year] => 1977-1978 ) [6] => stdClass Object ( [financial_year] => 1978-1979 )

when i was giving in foreach loop as

            foreach ($years as $year) {
            $data['result_data'][] = $this->report_model->get_historical_data($year);
        }

am getting php error as

A PHP Error was encountered

Severity: 4096

Message: Object of class stdClass could not be converted to string

Filename: database/DB_active_rec.php

Line Number: 42

what was the mistake am doing here

1
  • Are you using a framework or third party library of some sort? How is data access configured? Commented Jan 30, 2014 at 9:43

3 Answers 3

1

Change this $this->report_model->get_historical_data($year);

To this

$this->report_model->get_historical_data($year->financial_year);

Sign up to request clarification or add additional context in comments.

5 Comments

hi am having code as if ((count($years) >= 1) && $filter) { foreach ($years as $year) { $data['result_data'][] = $this->report_model->get_historical_data($year); } //print_r($data); } else { foreach ($years as $year) { $data['result_data'][] = $this->report_model->get_historical_data($year->financial_year); } //print_r($data); } foreach ($data['result_data'] as $key => $getValue){ echo $getValue[0][0]->state; } but am getting php error
A PHP Error was encountered Severity: Notice Message: Undefined offset: 0
Instead of $getValue[0][0]->state; use $getValue->state;
also you can use var_dump() function to debug variables. For example make var_dump($getValue) inside foreach loop. End give me the result
am getting an array of values with specifying array(50) { [0]=> object(stdClass)#174 (1) { ["state"]=> string(7) "Alabama" } [1]=> object(stdClass)#175 (1) { ["state"]=> string(7) "Alaska*" } [2]=> object(stdClass)#176 (1) { ["state"]=> string(7) "Arizona" }
0

try this

foreach ($years as $year) {
            $data['result_data'][] = $this->report_model->get_historical_data($year->financial_year);
        }

Comments

0

Only the collection is part of the array

Try something like this:

foreach (array $years as $key => $object) { 
     echo $object->financial_year;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.