How to loop through array of objects in PHP
Asked Answered
C

3

7

I'm very new to PHP and I need your help! I need to write backend for my app that receives json post and write data to json file. And I'm stuck with looping through array.

$postData = file_get_contents("php://input");
$request = json_decode($postData);
var_damp($request)

shows array:

array(2) {
  [0]=>
  object(stdClass)#1 (8) {
    ["name"]=>
    string(11) "Alex Jordan"
    ["email"]=>
    string(14) "[email protected]"
    ["phone"]=>
    int(123456789)
    ["street"]=>
    string(12) "street, str."
    ["city"]=>
    string(7) "Chicago"
    ["state"]=>
    string(7) "Chicago"
    ["zip"]=>
    string(5) "07202"
    ["$$hashKey"]=>
    string(8) "object:3"
  }
  [1]=>
  object(stdClass)#2 (8) {
    ["name"]=>
    string(15) "Michael Jonhson"
    ["email"]=>
    string(17) "[email protected]"
    ["phone"]=>
    float(11987654321)
    ["street"]=>
    string(12) "street, str."
    ["city"]=>
    string(11) "Los Angeles"
   ["state"]=>
   string(10) "California"
   ["zip"]=>
   string(5) "27222"
   ["$$hashKey"]=>
   string(8) "object:4"
 }
}

I'm trying to loop through the objects and getting error

Object of class stdClass could not be converted to string

Here is how I'm trying to do it:

    foreach($request as $i => $i_value) {
        echo $i_value;
    }
Culinarian answered 31/7, 2015 at 19:8 Comment(1)
echo $i_value->name; etc... Or foreach the object as well.Vernice
O
14

$i_value is the object. Because it's an object you cannot just echo it (unlike in JavaScript where you can cast any object to string).

You can echo specific properties of the object:

foreach($request as $i => $i_value) {
    echo $i_value->name;
}

Of course you could also use var_dump again to dump each object. print_r should work too.

Objects can only be casted to string like you do if they implement the __toString() magic method, but the objects created by json_decode are just simple StdClass objects that do not implement this. It's probably not your intention to do this at all, but if you're curious, you may have a look at json_decode to custom class to see how you may use a custom class instead of StdClass.

Opportuna answered 31/7, 2015 at 19:12 Comment(0)
Y
1

I had the same problem recently. I used a for loop to loop through the array which gave me an error of undefined offset. Using isset() solved the error of undefined offset. I know its too late to answer this question but here it is for someone who might be looking for it in future

$postData = file_get_contents("php://input");
$request = json_decode($postData);
// or you can do $postData = json_decode(file_get_contents("php://input"));
$arrayOfUsers = $request->data; // I used a key of data while sending the array via fetch API

for($x = 0; $x < count($arrayOfUsers); $x++)
{
    if(isset($arrayOfUsers[$x]))
    {
        $name = $arrayOfUsers[$x]->name;
        $email = $arrayOfUsers[$x]->email;
        $phone = $arrayOfUsers[$x]->phone;
        $street = $arrayOfUSers[$x]->street;
        // .... and so on
       // then you can do whatever you want with the data
    } else {
      echo "No Data Found";
    }
}
Yurikoyursa answered 11/7, 2021 at 8:27 Comment(0)
I
1

You can also use array_map(?callable $callback, array $array, array ...$arrays): array

  1. to get required properties of each object;
  2. or even alter its data.

This code covers both cases (sandbox_url):

<?php
$arr_of_objects[] = (object)['field_name' => 'test2', 'id' => 2];
$arr_of_objects[] = (object)['field_name' => 'test', 'id' => 1];

$array_of_names = array_map(function ($el) {
    return $el->field_name;
}, $arr_of_objects);

echo 'get field_name from array of objects' . "\n";
var_dump($array_of_names);

$replace_data_with = [
    1 => ['field_name' => 'replaced_name_1', 'id' => 777],
    2 => ['field_name' => 'replaced_name_2', 'id' => 999]
];

$changed_values = array_map(function ($el) use ($replace_data_with) {
    $el->field_name = $replace_data_with[$el->id]['field_name'];
    $el->id = $replace_data_with[$el->id]['id'];
    return $el;
}, $arr_of_objects);

echo 'alter data of each object' . "\n";
var_dump($changed_values);

Base array of Objects:

array(2) {
  [0]=>
  object(stdClass)#1 (2) {
    ["field_name"]=>
    string(5) "test2"
    ["id"]=>
    int(2)
  }
  [1]=>
  object(stdClass)#2 (2) {
    ["field_name"]=>
    string(4) "test"
    ["id"]=>
    int(1)
  }
}

Output:

get field_name from array of objects
array(2) {
  [0]=>
  string(5) "test2"
  [1]=>
  string(4) "test"
}
alter data of each object
array(2) {
  [0]=>
  object(stdClass)#1 (2) {
    ["field_name"]=>
    string(15) "replaced_name_2"
    ["id"]=>
    int(999)
  }
  [1]=>
  object(stdClass)#2 (2) {
    ["field_name"]=>
    string(15) "replaced_name_1"
    ["id"]=>
    int(777)
  }
}
Institutionalism answered 4/10, 2022 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.