phparraysoopmethodsreturn

How to accumulate the results from multiple methods into a single array


I am creating an API using the CodeIgniter.

I have managed to create a set of responses for various api calls.

public function test1($postcode)
{
    //run a query
    //get a response in an array structure 
    print_r(json_encode($response)); //print the json response
}

public function test2($postcode)
{
    //run a query
    //get a response in an array structure 
    print_r(json_encode($response)); //print the json response
}

so when I run these separately - it comes back fine.

eg.. http://localhost/codeigniter/index.php/api/test1/sw1

My major problem is trying to chain these various API calls into one master API call. So something like this.

public function master($postcode)
{
    //run a query
    $response = array(
        $this->test1($postcode),
        $this->test2($postcode)
    );

    //get a response in an array structure 
    print_r(json_encode($response)); //print the json response
}

but when I call this master API eg.. http://localhost/codeigniter/index.php/api/master/sw1

I get a weird result -- I get the two json responses - but then following it an empty array

{
    "similar-property-avg-sold": [
        [{
            "average": "651164.042021172"
        }]
    ]
} {
    "avg-property-sold-growth": {
        "data": [{
            "year": "2011",
            "average": "448696.91018672835"
        }, {
            "year": "2016",
            "average": "651164.042021172"
        }],
        "difference": 145.12336217118
    }
}
Array([0] => [1] => )

Solution

  • You are not returning the response from first two sub methods... So the master output will be null...

    public function test1($postcode){
        //run a query
    
        //get a response in an array structure 
        print_r(json_encode($response)); //print the json response
    
        //return response
        return $response;
    }
    
    public function test2($postcode){
        //run a query
    
        //get a response in an array structure 
        print_r(json_encode($response)); //print the json response
    
        //return response
        return $response;
    }