Converting PHP Arrays with Key Values to String Statement
Why we may need this let understand this first. For example when I was writing a database class I was using a method like that.
$params = [
'ORDER BY' => 'date DESC',
'LIMIT' => '0, 10'
];
Database::select('messages', $params)
To use them easily i need to combine the array which has key value then convert them into the string. So mysql code should be like this;
SELECT * FROM messages ORDER BY date DESC LIMIT 0, 10
I did this in a easiest way
$params = [
'ORDER BY' => 'date DESC',
'GROUP BY' => 'date',
'LIMIT' => '0, 15'
];
array_walk($params, function(&$i, $k){
$i = "$k $i";
});
$sql = implode(' ', $params);
echo $sql; // Result: ORDER BY date DESC GROUP BY date LIMIT 0, 15
Instead of assigning one variable and using in foreach loop, we used array_walk()
which is one of the array functions. And in anonym function we set our key to key-vaue. We combined the array by using implode()
and we got what we want
Comments
Popular Articles
Popular Tags
- #directive
- #Function
- #Json
- #Class
- #SASS
- #Form
- #Redirect
- #API
- #Special Characters
- #Special
- #Random
- #Generating
- #
- #Text
- #Ajax
- #URL
- #Encrypting
- #React
- #Show
- #timeAgo
- #PSR-4
- #Hide
- #DDOS Protection
- #DDOS
- #cURL
- #Logic For Displaying Posts
- #Error
- #Key
- #General Error
- #1364 Field
- #Abbreviation
- #Blade
- #Version
- #QR
- #QR Code Generating
- #Array
- #Arrays with Key Values to String Statement
- #Short Tag
- #Activate
- #Real Time
- #Socket.io
- #301
- #Custom Directives
- #Iframe Detection
- #Date
- #Characters
- #Insert
- #Autoloader
- #Composer
- #Reading
There are no comments, make the firs comment