0

Relatively new to Laravel and trying to create a REST api that will have as a response a json that is split between rows and cols of a query

So, the code used to generate the json is:

$r = array(
        'cols' => array_keys(get_object_vars(Dd_hr::take(2)->get())),
        'rows' => Dd_hr::take(2)->get()
    );
return response()->json($r, 201);

Basically, the json should look something like:

{"cols":[{"id", "user_name"}],"rows":[{"710206","user"}]}

But in fact it looks like:

{"cols":[],"rows":[{"id":"710206","user_name":"user"}]}

Could someone help me to solve this issue?

The result of dd(Dd_hr::take(2)->get()->toArray()):

array:2 [▼
  0 => array:27 [▼
    "rn" => "1"
    "id" => "710206"
    "user_name" => "user"
  ]
  1 => array:27 [▼
    "rn" => "2"
    "id" => "710207"
    "user_name" => "user"
  ]
]
3
  • Related: stackoverflow.com/questions/37157270/… Commented Sep 19, 2019 at 12:29
  • I saw that earlier while searching and it's not providing what I need, sorry.. I need a way to get the columns from a query that might have 5 or 11 columns, depending on the user selection Commented Sep 19, 2019 at 12:35
  • I've updated my answer for what it's worth. Commented Sep 19, 2019 at 14:50

1 Answer 1

1

Didn't find a way to do this properly so here goes the good old array_map.

This doesn't remove the "rn" key. If you want to chose the keys in the select you can, it'll even make creating the JSON easier since you'll already have the 'cols'.

$res_array = Dd_hr::take(2)->get()->toArray();

$cols = array_keys($res_array[0]);

$rows = array_map(function($row){
            return array_values($row);
        }, $res_array);

return response()->json(array('cols'=>$cols, 'rows'=>$rows), 201);

This returns : "{"cols":["rn","id","user_name"],"row":[["1","710206","user"],["2","710207","user"]]}"

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

2 Comments

The json looks like: {"cols":[0,1],"rows":[{"id":"710206","user_name":"user"}]}. Not the result expected..
Could you post the result of a dd(Dd_hr::take(2)->get()->toArray()) please ?

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.