Use the power of these PHP functions to sort your arrays

 HTML |  copy code |? 
001
If you’ve worked with PHP over any length of time, you’ll already be familiar with arrays — data structures that allow you to store multiple values in a single variable and operate on them as a set. Often, developers find it useful to sort these values, or array elements, into a sequence different from the default one used by PHP. To this end, PHP offers a wide variety of array sorting functions, which allow you to manipulate the arrangement of elements inside an array and re-sort them in a number of different ways. This tutorial will discuss some of the more important functions in this category.
002
 
003
Simple sorting
004
 
005
To begin, let’s consider the most simple case: simple sorting of an array’s elements from lowest to highest, either numerically or alphabetically. The PHP function to accomplish this is sort(), demonstrated in Listing A.
006
 
007
Listing A
008
 
009
<?php
010
 
011
$data = array(5,8,1,7,2);
012
sort($data);
013
print_r($data);
014
 
015
?>
016
 
017
Here’s the output:
018
Array 
019
(
020
[0] => 1
021
 
022
[1] => 2
023
 
024
[2] => 5
025
 
026
[3] => 7
027
 
028
[4] => 8
029
 
030
)
031
It’s also possible to reverse the simple sort demonstrated previously, with the rsort() function. This function rearranges an array’s elements from highest to lowest, either numerically or alphabetically. Listing B shows you an example.
032
 
033
Listing B
034
 
035
<?php 
036
$data = array(5,8,1,7,2);
037
rsort($data); print_r($data);
038
 
039
?>
040
And here’s the output:
041
Array 
042
(
043
[0] => 8
044
 
045
[1] => 7
046
 
047
[2] => 5
048
 
049
[3] => 2
050
 
051
[4] => 1
052
 
053
)
054
 
055
Sorting by key
056
 
057
When working with associative arrays, it’s often useful to re-sort the array by keys, again from highest to lowest. The ksort() function is designed for just this task; it maintains the key-value correlation during the sorting process. An example is presented in Listing C.
058
 
059
Listing C
060
 
061
<?php 
062
$data = array("US" => "United States", "IN" => "India", "DE" => "Germany", "ES" => "Spain");
063
ksort($data); print_r($data);
064
 
065
?>
066
And here’s the output:
067
Array 
068
(
069
[DE] => Germany
070
 
071
[ES] => Spain
072
 
073
[IN] => India
074
 
075
[US] => United States
076
 
077
)
078
You can also reverse-sort by key with the krsort() function, which is illustrated in Listing D.
079
 
080
Listing D
081
 
082
<?php 
083
$data = array("US" => "United States", "IN" => "India", "DE" => "Germany", "ES" => "Spain");
084
krsort($data); print_r($data);
085
 
086
?>
087
Here’s the output:
088
Array 
089
(
090
[US] => United States
091
 
092
[IN] => India
093
 
094
[ES] => Spain
095
 
096
[DE] => Germany
097
 
098
)
099
 
100
Sorting by value
101
 
102
If, instead, you’d prefer to sort your associative array by value instead of key, PHP’s got you covered there too. Simply use the asort() function instead of the aforementioned ksort() function, and you’re good to go! Listing E shows you how.
103
 
104
Listing E
105
 
106
<?php 
107
$data = array("US" => "United States", "IN" => "India", "DE" => "Germany", "ES" => "Spain");
108
asort($data); print_r($data);
109
 
110
?>
111
Here’s the output. Notice the difference between this and the output of ksort() above — in both cases, the sorting is alphabetic, but the sorting has been performed on different fields of the array. Notice also that the key-value association is maintained throughout; it’s only the manner in which the key-value pairs are ordered that has changed.
112
Array 
113
(
114
[DE] => Germany
115
 
116
[IN] => India
117
 
118
[ES] => Spain
119
 
120
[US] => United States
121
 
122
)
123
As you will have guessed by now, this sort can also be accomplished in reverse, with a call to arsort(). Listing F shows you an example.
124
 
125
Listing F
126
 
127
<?php 
128
$data = array("US" => "United States", "IN" => "India", "DE" => "Germany", "ES" => "Spain");
129
arsort($data); print_r($data);
130
 
131
?>
132
And here’s the output, with the values sorted in reverse-alphabetical order. Again, compare it with the output of krsort() to better understand the difference.
133
Array 
134
(
135
[US] => United States
136
 
137
[ES] => Spain
138
 
139
[IN] => India
140
 
141
[DE] => Germany
142
 
143
)
144
 
145
Natural-language sorting
146
 
147
PHP also has the unique ability to sort arrays the way humans would, using cognitive rather than computational rules. This feature is referred to as natural-language sorting, and it’s very useful when building fuzzy-logic applications. To see it in action, consider the simple example shown in Listing G.
148
 
149
Listing G
150
 
151
<?php 
152
$data = array("book-1", "book-10", "book-100", "book-5"); sort($data);
153
print_r($data);
154
 
155
natsort($data); print_r($data);?>
156
Here’s the output:
157
Array 
158
(
159
[0] => book-1
160
 
161
[1] => book-10
162
 
163
[2] => book-100
164
 
165
[3] => book-5
166
 
167
)
168
 
169
Array
170
 
171
(
172
 
173
[0] => book-1
174
 
175
[3] => book-5
176
 
177
[1] => book-10
178
 
179
[2] => book-100
180
 
181
)
182
The difference should be clear: The second sort order is more intuitive and “human,” while the first one is more algorithmic and “computational.”
183
 
184
Reverse natural-language sorting? Sure! Just use the array_reverse() function on the output of natsort(), as shown in Listing H.
185
 
186
Listing H
187
 
188
<?php 
189
$data = array("book-1", "book-10", "book-100", "book-5");
190
natsort($data); print_r(array_reverse($data));
191
 
192
?>
193
And here’s the output:
194
Array 
195
(
196
[0] => book-100
197
 
198
[1] => book-10
199
 
200
[2] => book-5
201
 
202
[3] => book-1
203
 
204
)
205
 
206
Sorting by user-defined rules
207
 
208
PHP also lets you define your own sorting algorithm by creating your own comparison function and passing it to the usort() function. The comparison function must return a number less than 0 if the first argument is to be considered “less” than the second, and a number greater than 0 if the first argument is to be considered “greater” than the second.
209
 
210
Listing I shows an example, which sorts array elements by their length, with the shortest items first:
211
 
212
Listing I
213
 
214
<?php 
215
$data = array("joe@host.com", "john.doe@gh.co.uk", "asmithsonian@us.info", "jay@zoo.tw");
216
usort($data, 'sortByLen');
217
 
218
print_r($data); function sortByLen($a, $b) {
219
 
220
if (strlen($a) == strlen($b)) {
221
 
222
return 0;
223
 
224
} else {
225
 
226
return (strlen($a) > strlen($b)) ? 1 : -1;
227
 
228
}
229
 
230
}
231
 
232
?>
233
In this case, I’ve created my own comparison function, which uses the strlen() function to compare the number of characters in each string and return a value of 1, 0 or -1, respectively. This return value then forms the basis for deciding the arrangement of elements. Here’s the output:
234
Array 
235
(
236
[0] => jay@zoo.tw
237
 
238
[1] => joe@host.com
239
 
240
[2] => john.doe@gh.co.uk
241
 
242
[3] => asmithsonian@us.info
243
 
244
)
245
 
246
Multidimensional sorting
247
 
248
Finally, PHP also lets you perform some fairly complex sorting on multidimensional arrays — for example, ordering a set of nested arrays first by one common key and then by another. This is similar to using SQL’s ORDER BY clause on multiple fields to order data sets in a particular way. To see how this works, take a look at the example shown in Listing J.
249
 
250
Listing J
251
 
252
<?php 
253
$data = array(
254
array("id" => 1, "name" => "Boney M", "rating" => 3),
255
 
256
array(”id” => 2, “name” => “Take That”, “rating” => 1),
257
 
258
array(”id” => 3, “name” => “The Killers”, “rating” => 4),
259
 
260
array(”id” => 4, “name” => “Lusain”, “rating” => 3),
261
 
262
); foreach ($data as $key => $value) {
263
 
264
$name[$key] = $value['name'];
265
 
266
$rating[$key] = $value['rating'];
267
 
268
}
269
 
270
array_multisort($rating, $name, $data); print_r($data);?>
271
Here, I’ve simulated a data set of rows and columns in the $data array. I’ve then used the array_multisort() function to re-sort the data set, first by rating and then, in cases where ratings are equal, by name. The output is as follows:
272
Array 
273
(
274
[0] => Array
275
 
276
(
277
 
278
[id] => 2
279
 
280
[name] => Take That
281
 
282
[rating] => 1
283
 
284
) [1] => Array
285
 
286
(
287
 
288
[id] => 1
289
 
290
[name] => Boney M
291
 
292
[rating] => 3
293
 
294
)
295
 
296
[2] => Array
297
 
298
(
299
 
300
[id] => 4
301
 
302
[name] => Lusain
303
 
304
[rating] => 3
305
 
306
)
307
 
308
[3] => Array
309
 
310
(
311
 
312
[id] => 3
313
 
314
[name] => The Killers
315
 
316
[rating] => 4
317
 
318
)
319
 
320
)
321
This array_multisort() function is one of the most powerful sorting functions available in PHP and has a variety of uses. In addition to what you saw in the example, it can be used to sort multiple independent arrays, using elements of one as the basis for sorting the next, and it can be used to sort database result sets.
322
 
323
The examples should have given you insight into the various array sorting functions available in PHP and showed you some of the power hidden inside PHP’s array manipulation toolkit. Happy coding!

Generate JSON file dynamically using PHP

 PHP |  copy code |? 
01
<?php 
02
 $sql=mysql_query("select * from Posts limit 20"); 
03
 
04
 $response = array();
05
 $posts = array();
06
 $result=mysql_query($sql);
07
 while($row=mysql_fetch_array($result)) 
08
 { 
09
 $title=$row['title']; 
10
 $url=$row['url']; 
11
 $posts[] = array('title'=> $title, 'url'=> $url);
12
 } 
13
 $response['posts'] = $posts;
14
 $fp = fopen('results.json', 'w');
15
 fwrite($fp, json_encode($response));
16
 fclose($fp);
17
?> 

concat if condition inside HTML – “Tenary Operator”

Usually we cannot concat if condition inside HTML.  But there is another alternate where we can perform the same operation through the Tenary Operator.  Here is the code how to do so,

Wrong Method:

 PHP |  copy code |? 
1
for($i=0;$i<count($arrSql);$i++)
2
     $opt.="<option". if($_GET['pId'] == $arrSql[$i][0]){ echo "Selected";} ."value=".$arrSql[$i]&nbsp;                                           [0].">".$arrSql[$i][1]."</option>";

Right Method:

 PHP |  copy code |? 
1
for ($i=0;$i<count($arrSql);$i++) {
2
     $opt .= "<option"&nbsp;. ($_GET['pId'] == $arrSql[$i][0] ? " selected" : '')&nbsp;."value=".$arrSql[$i][0].">".$arrSql[$i]."</option>";

HOW TO OPEN LINK IN NEW TAB USING JAVASCRIPT

Method 1:

 Javascript |  copy code |? 
1
function open_in_new_tab(url)
2
{
3
      window.open(url, '_blank');
4
      window.focus();
5
}

Method 2:

 jquery |  copy code |? 
1
$('a').click(function() {
2
  $(this).attr('target', '_blank');
3
 });

Method 3:

 jquery |  copy code |? 
1
$(document).ready(function() {
2
   $('#NewTab').click(function() {
3
        $(this).target = "_blank";
4
        window.open($(this).prop('href'));
5
        return false;
6
   });
7
});

HOW TO ESCAPE SINGLE QUOTES IN JAVASCRIPT

 PHP |  copy code |? 
1
$strLocation = 'http://www.google.com';
2
$strLink = "HI there";
3
 (or)
4
 
5
$strLink = 'HI there';
6
print $strLink; 

Using ‘ is html special char which remains undetected during string operations and will appear only in browser.  We can use ( &#39;) this which is equal to (‘).  This will not be indexed in php code and will be affected when compiled through html.
Using \ simple escapes the string

How to show and hide the div with respect to its class.

Class name for DIV should be common and ID should be different and style.display also should be none.

 HTML |  copy code |? 
1
<div class='hiddenClass' id='specific_id' style='display:none'>

In Javascript code hide the div with respect to class name and then block the div with respect to its specific id.

 jquery |  copy code |? 
1
$('.hiddenClass').hide();
2
document.getElementById('##specefic id##').style.display = 'block';

 

1 2 3  Scroll to top