Traversing Object array and accessing a value

Asked

Viewed 14,457 times

3

Good afternoon guys, I’m having a difficulty, where I need to access an element of an array of OBJECTS, I’m not being able to access with foreach, or for. I need your help!

The array of objects:

Array
(
    [0] => stdClass Object
        (
            [pk] => 1343200701115549070
        )

    [1] => stdClass Object
        (
            [pk] => 1339248324134135231
        )

    [2] => stdClass Object
        (
            [pk] => 1338844272896371640
        )

    [3] => stdClass Object
        (
            [pk] => 1338841774089501872
        )

    [4] => stdClass Object
        (
            [pk] => 1338838365890273563
        )

I need to take the values of "pk" to put in another variable. To complement the explanation, this array is a json_encode file, where I open the file and turn it into json_decode:

$file = new SplFileObject($caminho);
        while (!$file->eof()) {
           $id_line1 = $file->fgets();
        }
        $id_line = json_decode($id_line1);

Vlw hug!!

  • 1

    Make a foreach and call the property so $item->pk

3 answers

6


With this iteration you get the key content:

foreach ($array_de_objetos as $key => $value){
    echo $value->pk;
}
  • Wow, man I tried everything but this kkkk. It helped a lot thanks, big hug!!!

1

// Foreach creates a copy

$array = [
  "foo" => ['bar', 'baz'],
  "bar" => ['foo'],
  "baz" => ['bar'],
  "batz" => ['end']
];

// while(list($i, $value) = each($array)) { // Try this next
foreach($array as $i => $value) {
  print $i . "\n";
  foreach($value as $index) {
    unset($array[$index]);
  }
}

print_r($array); // array('baz' => ['end'])

You have an object interpreted within a list, making access more complicated, make sure you understand how to access this variable outside the array, and do the same within the array. This example here This array inside array and Coo correctly run the loop.

0

I’m seeing a code where the interaction variable would be $id_line:

    $file = new SplFileObject($caminho);
    while (!$file->eof()) 
    {
        $id_line1 = $file->fgets();
    }
    $id_line = json_decode($id_line1);

   foreach($id_line as $line)
   {
     $textoPK = $line->pk;
   }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.