I. array processing functions:
Intoxicating: array processing functions are very common in PHP development. Learning array processing functions is crucial. array Processing functions involve the creation of arrays, the conversion of strings from arrays to XML, and the conversion of arrays to JSON. array detection. the array is merged into shards. number of arrays. obtain all values in the array and all key values in the array [subscript]
1. Create an array:
$ New = array ();
2. implode (separator, str) concatenates array value data by specified characters
Copy codeThe Code is as follows:
$ Arr = array ('hello', 'World! ', 'Beautiful', 'day! ');
Echo implode ("", $ arr); Output
Hello World! Beautiful Day!
3. count (arr) calculates the number of units in the array or the number of attributes in the object.
4. is_array (arr) checks whether the variable is an array.
5. The array_rand () function randomly selects one or more elements from the array and returns them.
Copy codeThe Code is as follows:
$ A = array ("a" => "Dog", "B" => "Cat", "c" => "Horse ");
Print_r (array_rand ($ a, 1 ));
Output: B
Copy codeThe Code is as follows:
$ A = array ("a" => "Dog", "B" => "Cat", "c" => "Horse ");
Print_r (array_rand ($ a, 2); View Code
Array ([0] => c [1] => B)
6. The array_sum () function returns the sum of all values in the array.
Copy codeThe Code is as follows:
$ A = array (0 => "5", 1 => "15", 2 => "25 ");
Echo array_sum ($ );
Output: 45
7. The array_slice () function extracts a value from the Array Based on the Conditions and returns it.
Copy codeThe Code is as follows:
$ A = array (0 => "Dog", 1 => "Cat", 2 => "Horse", 3 => "Bird ");
Print_r (array_slice ($ a, 1, 2); View Code
Array ([0] => Cat [1] => Horse)
8. The array_count_values () function is used to count the number of occurrences of all values in the array.
Copy codeThe Code is as follows:
$ A = array ("Cat", "Dog", "Horse", "Dog ");
Print_r (array_count_values ($ a); output:
Array ([Cat] => 1 [Dog] => 2 [Horse] => 1)
3. Convert arrays to XML
Copy codeThe Code is as follows:
Function array2xml ($ array, $ tag ){
Function ia2xml ($ array ){
$ Xml = "";
Foreach ($ array as $ key => $ value ){
If (is_array ($ value )){
$ Xml. = "<$ key>". ia2xml ($ value). "</$ key> ";
} Else {
$ Xml. = "<$ key>". $ value. "</$ key> ";
}
}
Return $ xml;
}
Return simplexml_load_string ("<$ tag>". ia2xml ($ array). "</$ tag> ");
}
$ Test ['type'] = 'lunch ';
$ Test ['time'] = '12: 30 ';
$ Test ['menu '] = array ('entree' => 'salad', 'maincourse' => 'steak ');
Echo array2xml ($ test, "meal")-> asXML ();
Output:
Copy codeThe Code is as follows:
<? Xml version = "1.0"?>
<Meal>
<Type> lunch </type>
<Time> 12: 30 </time>
<Menu>
<Entree> salad </entree>
<Maincourse> steak </maincourse>
</Menu>
</Meal>