Home > Software engineering >  How do I add new keys and value to an array before converting to JSON?
How do I add new keys and value to an array before converting to JSON?

Time:04-08

How do I add additional key and value to my array in every loop before converting it to json?

I'm trying to add a additional key and value to accommodate the 'Edit' and 'Delete" button before converting it on JS DataTables.

My sample current array

$results:

array:97 [
 0 => {#1
   "username": "azura"
   "gem": "emerald"
   "color": null
 }

 1 => {#2
   "username": "azuren"
   "gem": "ruby"
   "color": "red"
 }
...]

My expected array after adding. I want to inject a button made of string.

 0 => {#1
   "username": "azura"
   "gem": "emerald"
   "color": null
   "action": "<button id="edit" remove" >Delete</button>"
 }

 1 => {#2
   "username": "anngeetan"
   "gem": "ruby"
   "color": "red"
   "action": "<button id="edit" remove" >Delete</button>"
 }
...]

Then on my larvel php i will convert it to DataTables Json to accomodate the new 'action' item to my js

My js

$('#mytable').DataTable({
 columns: [
     'data': 'azuren',
     'data': 'gem',
     'data': 'color',
     'data': 'action',
 ]
}):

My php controller

public function get_table(Request $request)
{
    $table = $request['selected-table'];
    $results = DB::select("SELECT * from $table");
    
    //add the 'action' item somewhere here.

    return datatables($results)->make(true);
}

PS: Feel free to suggest a new method if there a better way or the optimization is bad ( I also have an array that has 20,000 entries).

CodePudding user response:

You can do this way

https://yajrabox.com/docs/laravel-datatables/master/add-column

$table = $request['selected-table'];
$results = DB::select("SELECT * from $table");

 return datatables($results)
     ->addColumn('action', function ($row) { // added action key 
          return "<button id='edit' class='edit-btn'></button>
                 <button id='remove' class='delete-btn'>Delete</button>";
     })->make(true);
  • Related