PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

[FIXED] How do I add new keys and value to an array before converting to JSON?

 April 19, 2022     datatables, laravel, php     No comments   

Issue

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" class="edit-btn></button>
              <button id="remove" class="delete-btn">Delete</button>"
 }

 1 => {#2
  +"username": "anngeetan"
  +"gem": "ruby"
  +"color": "red"
  +"action": "<button id="edit" class="edit-btn></button>
              <button id="remove" class="delete-btn">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).


Solution

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);


Answered By - Noman Saleem
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing