Joseph
Joseph

Reputation: 733

Looping through array in PHP returned Object of class stdClass could not be converted to string

I am sending an array over HTTP POST to backend API which is PHP.

js

var form_data = [];
for (var k = 0; k < $scope.Tablelist.length; k++){
  if($scope.Tablelist[k].selected == true){
    var id = $scope.Tablelist[k].id;
    var docno = $scope.Tablelist[k].quote_no;
    form_data.push({id: id, docno:docno})
  }
}
if(form_data.length>0){
  $http({
    method: 'POST',
    url: "api/purchase/purchase.php",
    data: {
      modul: 'PRICE',
      action: 'delete',
      form_data: form_data,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    }
  })

PHP

$form_data = (array)$request->form_data;
foreach ($form_data as $key => $value) {
     echo "Key: $key; Value: $value";
}

it gave me an error Object of class stdClass could not be converted to string.

I am trying to get the value of id and docno of each array.

How can i do that?

var_dump($form_data)

"array(3) {↵ [0]=>↵ object(stdClass)#3 (2) {↵ ["id"]=>↵ string(1) "6"↵ ["docno"]=>↵ string(5) "test4"↵ }↵ [1]=>↵ object(stdClass)#4 (2) {↵ ["id"]=>↵ string(1) "7"↵ ["docno"]=>↵ string(5) "test3"↵ }↵ [2]=>↵ object(stdClass)#5 (2) {↵ ["id"]=>↵ string(1) "4"↵ ["docno"]=>↵ string(5) "test2"↵ }↵}↵"

var_dump($request->form_data)

"array(3) {↵ [0]=>↵ object(stdClass)#3 (2) {↵ ["id"]=>↵ string(1) "6"↵ ["docno"]=>↵ string(5) "test4"↵ }↵ [1]=>↵ object(stdClass)#4 (2) {↵ ["id"]=>↵ string(1) "7"↵ ["docno"]=>↵ string(5) "test3"↵ }↵ [2]=>↵ object(stdClass)#5 (2) {↵ ["id"]=>↵ string(1) "4"↵ ["docno"]=>↵ string(5) "test2"↵ }↵}↵"

Upvotes: 1

Views: 321

Answers (2)

Murad Hasan
Murad Hasan

Reputation: 9583

Remember one things, The type casting of like this never convert the inner Object. So you need to access them using the -> sign.

And your $value is also an array you can't echo it.

From your var_dump of objects, you can notice that the inner array looks an object not array. So i suggest to use this as object.

Important: You can encode as json the form_data in your JavaScript code and in PHP just decode with true properties so that you can get an associative array.

As per your requirement, I am trying to get the value of id and docno of each array.

$form_data = (array) $request->form_data;
foreach ($form_data as $key => $value) {
    echo "Key:".$key;
    echo $value->docno." and ".$value->id;
}

Try to access the inner array as object or again type case it.

Note: Also you can use get_object_vars for type case an object to an array. More details

Upvotes: 1

Sibiraj PR
Sibiraj PR

Reputation: 1481

You can try like this.

$form_data = (array)$request->form_data;
foreach ($form_data as $key => $value) {
 echo "Key: $value->id; Value: $value->docno";
}

Upvotes: 1

Related Questions