0

I'm using Lumen to set up a microservice for polling a database frequently and distribute the dataset through a wamp router to multiple clients. The database query is stored in a stored procedure, that's why i do the following in my controller:

$result = DB::select($query);

return $result;

The return gives the following dataset:

[
    {
        "0": "012345",
        "1": "Moby Dick",
        "2": "Herman Melville",
        "3": "Hardcover",
        "isbn": "012345",
        "title": "Moby Dick",
        "author": "Herman Melville",
        "type": "Hardcover"
    },
    {
        "0": "123456",
        "1": "Laravel: Code Bright",
        "2": "Dayle Rees",
        "3": "Ebook",
        "isbn": "123456",
        "title": "Laravel: Code Bright",
        "author": "Dayle Rees",
        "type": "Ebook"
    },
    {
        "0": "234567",
        "1": "Easy Laravel 5",
        "2": "W.J. Gilmore",
        "3": "Ebook",
        "isbn": "234567",
        "title": "Easy Laravel 5",
        "author": "W.J. Gilmore",
        "type": "Ebook"
    }
]

I want to remove the numeric key-value pairs prepending the associative key-value pairs. How can i do that?

Thanks in advance!

Edit: things I tried:

$result = DB::select($query)->get(); // Gives: Call to a member function get() on array. For obvious reasons

A dirty hack like Matei stated: Looping through the array and removing the KVP where the key is numeric. Which works, but I think the Laravel/Lumen framework offers cleaner solutions, which I am not able to find.

Jievie
  • 73
  • 1
  • 7
  • 1
    What have you tried? Show us the code you tried. SO is not a free coding service. – Jamie Harding Dec 16 '15 at 08:45
  • @JamieSterling, I updated my question. Not looking for a free coding service. I already get it working on a dirty way like Matei stated, but i'm aiming for clean code, and getting the most out of the laravel/lumen framework. So the question is related to that framework. – Jievie Dec 16 '15 at 09:04

1 Answers1

0

In config/database.php you can change 'fetch' => PDO::FETCH_CLASS, to 'fetch' => PDO::FETCH_ASSOC,

or

You can use array_reduce and array_filter like:

$result = json_decode(DB::select($query), true);

$result = array_reduce($result, function ($result, $item) {
     $result[] = array_filter($result, function ($key) {
         return !is_numeric($key);
     }, ARRAY_FILTER_USE_KEY)

     return $result;
}, array());

return json_encode($result);

NOTE: If the DB stmt is returning an array, rather than a json encoded string, then you must remove the json_decode and json_encode functions calls.

Mihai Matei
  • 24,166
  • 5
  • 32
  • 50