Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I have read a number of the answers on this but I am not getting something. I have an object that retrieves data from a file and puts into an array format and I am trying to get the data into a variable in the calling file so that I can work with the data.

 calling.php

    $x = new obj();
    $x -> method_y();

 objectfile.php

    public function method_y(){
       ..... code does stuff .....
       print_r($array);
    }

    array(
         [0] => array
             (
                 [key1] => value1
                 [key2] => value2
                 [key3] => value3
             )
          [1] => array
             (
                 [key1] => value1
                 [key2] => value2
                 [key3] => value3
              )
    )

Is is better to use an echo, return, or print from the method and should I use the json_encode to return it. How do I get the returned data into out of the object into something I can work with. For instance using the json_encode in the method I get back json but the json_decode wants a string.

Again I have read a number of answers on this but I am not getting it.

Thanks in advance.

share|improve this question
up vote 0 down vote accepted

You can as well return the array itself, and then traverse the array using for loops, maybe something like this

public function method_y(){
    ..... code does stuff .....
    return $array;
}

$var = $x -> method_y();

foreach($var as $element) {
    foreach($element as $key => $value) {
          echo $key;
          echo $value;
    }
}
share|improve this answer
    
I changed my calling file to have $j = $x -> method_y(); and when I try to loop over $j I get the error Invalid argument supplied for foreach(). – user1088014 Nov 19 '14 at 17:27
    
var_dump($j); tell me the result of this – bSaraogi Nov 19 '14 at 17:31
    
NULL. I tried return $array and print_r($array) from the method. The print_r puts it to the screen but the $j is NULL. Not sure if this makes a difference but I am running from command line using 5.6 on Windows 7. – user1088014 Nov 19 '14 at 17:34
    
The system has nothing to do with it, are you sure you are generating the array to be returned right? – bSaraogi Nov 19 '14 at 17:39
    
Ok this is where being rusty meets Doh! I am using a call to a method_x to call method_y. I have a return in method_y but not in method_x. Getting data on the screen was leading me in the wrong direction. Problem solved. Thanks. – user1088014 Nov 19 '14 at 17:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.