-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?

4
  • you should check if $value is an array or string before echo :) Commented Mar 11, 2019 at 13:59
  • 1
    use a recursive function, a function that calls itself if the next item is an object etc. Commented Mar 11, 2019 at 14:00
  • 2
    Possible duplicate of Traversing through nested objects and arrays in php Commented Mar 11, 2019 at 14:03
  • If you want to have the data just visible in a structured format, you could simply use echo json_encode($object); Commented Mar 11, 2019 at 14:08

1 Answer 1

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 ?

Sign up to request clarification or add additional context in comments.

2 Comments

Although your code might be good and you explained, this is just reinventing the wheel. Just use print_r(), var_dump() or var_export().
Oh yeah of course I was just explaining, it's better to understand first and then use what already exists ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.