1

I have an array which I am getting from my database. For instance:

$db_record = $this->search_model->search_Employee();
foreach ($db_record as $db_data) {
    echo $db_data->phone_number;
}

In above example I am able to fetch the record without any issue, but I want to add other data in $db_data afterwards.

foreach ($db_record as $db_data) {
    echo $db_data->phone_number;
    $db_data[]['new_value']='prashant';
}

but $db_data[]['new_value']='prashant'; throwing below error

Cannot use object of type stdClass as array in

It will great if someone can help me as struggeling more than 5 hours.

4
  • 1
    because your $db_data is an object, not an array, so you can not use it as an array: $db_data[]. Commented Oct 28, 2014 at 13:36
  • 1
    $db_data->foo = 'prashant'. Commented Oct 28, 2014 at 13:36
  • stackoverflow.com/questions/11396033/stdclass-to-array Commented Oct 28, 2014 at 13:37
  • Cast it to an array before adding it Commented Oct 28, 2014 at 13:38

4 Answers 4

6

Try $db_data->new_value ='prashant';

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

1 Comment

I get the following error: Attempt to assign property of non-object
3

You have to create a new stdClass object:

$tmp = new stdClass;
$tmp->new_value = 'prashant';
$db_data[] = $tmp;

Comments

0
 foreach ($agent as $key => $value) {

   $value->any = 'ssds';
}

try to use the $value instead key and object

Comments

-1

Your $db_data is an object you can't use them like an array. Yout have to add a property to your object and init them with an empty array.

Example:

foreach ($db_record as $db_data) {
    echo $db_data->phone_number;
    $db_data->empty_array=array();
    $db_data->empty_array['new_value']='prashant';
}

1 Comment

This is a not a very useful answer. It doesn't go to explain the simplest solution available thus can be really confusing.

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.