Traversing array of objects and accessing a value

2

Good afternoon, I have a difficulty, where I need to access an element of an array of OBJECTS, I'm not able to access with the 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 get the values from "pk" to putting in another variable. To complement the explanation, this array is a file in json_encode, where I open the file and transform it into json_decode:

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

I love you     

asked by anonymous 11.10.2016 / 15:56

3 answers

4

With this iteration you take the contents of the key:

foreach ($array_de_objetos as $key => $value){
    echo $value->pk;
}
    
11.10.2016 / 16:32
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 interpreted object inside a list, making access more complicated, make sure you understand how to access that variable outside the array, and do the same inside the array. This example throws an array inside the array and correctly executes the loop.

    
11.10.2016 / 16:02
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;
   }
    
11.10.2016 / 16:13