ashura91
ashura91

Reputation: 441

'Trying to get property of non-object' after using array_unshift

I have an object :

$data = '[{"NO":"1","ID_JPS":"AAA"},{"NO":"2","ID_JPS":"BBB"}]';
$data_ori = json_decode($data);

I am getting the NO and ID_JPS properties within a for loop.

for($i=0; $i < count($data_ori); $i++){
   echo $id_item = "NO = " . $data_ori[$i]->NO . " & ID_JPS = " . $data_ori[$i]->ID_JPS;
}

I'd like to insert a blank data into $data_ori so I use array_unshift():

$data_blank = array( 'NO' => 'NULL','ID_JPS' => 'NULL');
array_unshift($data_ori,$data_blank);

But, after doing that, my for loop stops working. The error message is:

Message: Trying to get property of non-object.

How do I get the data from the inserted item?

Upvotes: 1

Views: 31

Answers (1)

miken32
miken32

Reputation: 42715

That's because you're inserting an array, not an object. Easiest is just to cast it:

$data_blank = (object)array( 'NO' => 'NULL','ID_JPS' => 'NULL');

Upvotes: 1

Related Questions