0

I'm having a difficult time trying to get back a single array, which I can then return as JSON.

The Model:

class CoverageLimit extends Eloquent {

    protected $table = 'webapp_limit_tbl';

    public static function index($code,$plan_type,$income_tier){
        $data =  CoverageLimit::where('limitcode', $code)
        ->where('plantypecode', $plan_type)
        ->where('incometiercode', $income_tier)
        ->get(array('limitcode','limit_desc'));
        return print_r($data->toArray());
    }

}

The Controller:

$limits = array();
    foreach($pieces as $coverage_limit) {
    $limits = array_merge($limits, coveragelimit::index($coverage_limit,$plan_type,$income_tier));
//this now works thanks to suggestion below
    } 
return $limits;

Returns:

Array
(
    [0] => Array
        (
            [limitcode] => L0001
            [limit_desc] => $1M per claim / $2M annual aggregate
        )

)
Array
(
    [0] => Array
        (
            [limitcode] => L0002
            [limit_desc] => $2M per claim/ $2M annual aggregate
        )

)
[true,true]

The goal is to output the following JSON data via json_encode($limits):

[{"limitcode":"L0001","limit_desc":"$1M per claim / $2M annual aggregate"},{"limitcode":"L0002","limit_desc":"$2M per claim / $2M annual aggregate"}]

I think what I need is a single array like below in order to accomplish this, but I can't seem to make it happen.

Array
(
    [0] => Array
        (
            [limitcode] => L0001
            [limit_desc] => $1M per claim / $2M annual aggregate
        ),
    [1] => Array
        (
            [limitcode] => L0002
            [limit_desc] => $2M per claim/ $2M annual aggregate
        )

)

I would be grateful for any help on how I could merge this return into a single array for valid json output. Or if there is a way to return it from the foreach as one array. Thanks.

1 Answer 1

1

First, do not use return print_r($data->toArray());

That is incorrect. Just do return $data->toArray() and it should work just fine.

The problem is that print_r returns a boolean and outputs to stdout a text representation of your data structure. That is why you see that annoying [true, true] at the end of your output example. The array you are attempting to json_encode is actually just an array with two values of true returned from print_r.

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

1 Comment

Thank you, that was the ticket!

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.