-2

I'm iterating over an array of objects, some of them nested in a non-uniform way. I'm doing the following:

foreach($response['devices'] as $key => $object) {
    foreach($object as $key => $value) {
        echo $key . " : " . "$value . "<br>";
    }
}

Which works...until it hits the next embedded array/object, where it gives me an 'Notice: Array to string conversion in C:\xampp\htdocs\index.php on line 65' error

I'm relatively new to PHP and have thus far only had to deal with uniform objects. This output is far more unpredictable and can't be quantified in the same way. How can I 'walk' through the data so that it handles each array it comes across?

daz-wuk
  • 17
  • 1
  • 5
  • you should check if $value is an array or string before echo :) – treyBake Mar 11 '19 at 13:59
  • 1
    use a recursive function, a function that calls itself if the next item is an object etc. – ArtisticPhoenix Mar 11 '19 at 14:00
  • 2
    Possible duplicate of [Traversing through nested objects and arrays in php](https://stackoverflow.com/questions/43129601/traversing-through-nested-objects-and-arrays-in-php) – yivi Mar 11 '19 at 14:03
  • If you want to have the data just visible in a structured format, you could simply use `echo json_encode($object);` – Daniel W. Mar 11 '19 at 14:08

1 Answers1

0

You should make a recusive function this means, the function call itself until a condition is met and then it returns the result and pass through the stack of previously called function to determine the end results. Like this

<?php
// associative array containing array, string and object
$array = ['hello' => 1, 'world' => [1,2,3], '!' => ['hello', 'world'], 5 => new Helloworld()];

// class helloworld
class Helloworld {

    public $data;

    function __construct() {
        $this->data = "I'm an object data";
    }
}

//function to read all type of data
function recursive($obj) {
    if(is_array($obj) or is_object($obj)) {
        echo ' [ '.PHP_EOL;
      foreach($obj as $key => $value) {
          echo $key.' => ';
          recursive($value);
      }  
      echo ' ] '.PHP_EOL;
    } else {
        echo $obj.PHP_EOL;
    }
}


// call recursive
recursive($array);

?>

This prints something like this :

 [ 
hello => 1
world =>  [ 
0 => 1
1 => 2
2 => 3
 ] 
! =>  [ 
0 => hello
1 => world
 ] 
5 =>  [ 
data => I'm an object data
 ] 
 ] 

I hope this helps ?

RLoris
  • 526
  • 5
  • 14
  • 1
    Although your code might be good and you explained, this is just reinventing the wheel. Just use `print_r()`, `var_dump()` or `var_export()`. – Daniel W. Mar 11 '19 at 14:57
  • Oh yeah of course I was just explaining, it's better to understand first and then use what already exists ;) – RLoris Mar 11 '19 at 15:00