PHP utility functions, PHP functions
For the first time, write some of the more useful functions of your own work.
Array functions:
1 Array_column--Returns the column specified in the array
Usage One: Returns the column specified in the array
Application scenario: Take out the class ID and go to other tables to find out other information about the students.
Benefit: Reduce the number of queries to the database (all information is detected once by ID)
Liezi:
$records = Array (
Array
' id ' = 2135,
' first_name ' = ' John ',
' last_name ' = ' Doe ',
),
Array
' id ' = 3245,
' first_name ' = ' Sally ',
' last_name ' = ' Smith ',
)
);
$first _names = Array_column ($records, ' id ');
Print_r ($first _names);
Results
Array (' 2135 ', ' 3245 ');
?>
Usage Two: Use the ID of the two-dimensional array as the key of the array
Scenario: Extracting data by array[' ID ']
Benefit: Use Array_column instead of foreach to set the ID of the two-dimensional array as the key of the array, the code is concise, and the system function is called to improve efficiency.
Liezi:
$records = Array (
Array
' id ' = 2135,
' first_name ' = ' John ',
' last_name ' = ' Doe ',
),
Array
' id ' = 3245,
' first_name ' = ' Sally ',
' last_name ' = ' Smith ',
)
);
Using the Foreach
$records _key = Array ();
foreach ($records as $k = = $v) {
$records _key[$v [' id ']] = $v;
}
Print_r ($first _names);
Call Array_column
$records _key = Array_column ($records, NULL, ' id ');
Print_r ($first _names);
?>
Results
Array (
[2135] = = Array (
[id] = 2135
[First_Name] = John
[Last_Name] = Doe
)
[3245] = = Array (
[id] = 3245
[First_Name] = Sally
[Last_Name] = Smith
)
)
2 Array_multisort--Sort multiple arrays or multidimensional arrays
Usage One: multidimensional array sorting
Scenario: Sort data in descending order by price, sorted by sales ascending
Benefits:
Liezi:
$data [] = Array (' price ' = +, ' sale_num ' = 2);
$data [] = Array (' price ' = +, ' sale_num ' = 1);
$data [] = Array (' price ' = =, ' sale_num ' = 6);
$data [] = Array (' price ' = = 98, ' sale_num ' = 2);
$data [] = Array (' price ' = +, ' sale_num ' = 6);
$data [] = Array (' price ' = +, ' sale_num ' = 7);
Get a list of columns
$price = Array_column ($data, ' price ');
$sale _num= array_column ($data, ' sale_num ');
The $data as the last parameter, sorted by the Universal key
Array_multisort ($price, Sort_desc, $sale _num, SORT_ASC, $data);
?>
Results
Price | Sale_num-------+-------- 98 | 2 | 1 | 6 | 6 | 2 | 7
Not to be continued!
http://www.bkjia.com/PHPjc/1117668.html www.bkjia.com true http://www.bkjia.com/PHPjc/1117668.html techarticle PHP utility Functions, PHP functions for the first time, write some of their own work more practical functions. Array functions: 1 Array_column--Returns the specified column usage in the array: return ...