Php array required

Source: Internet
Author: User
Php array required

  1. Foreach ($ prices as $ key => $ value)
  2. Echo $ key. '=>'. $ value .'
    ';

The following code uses the each () structure to print the content of the $ prices array:

  1. While ($ element = each ($ prices ))
  2. {
  3. Echo $ element ['key'];
  4. Echo '-';
  5. Echo $ element ['value'];
  6. Echo'
    ';
  7. }

The each () function returns the current element of the array and uses the next element as the current element. Because the while loop calls the each () function, it returns each element in the array in order, and when it reaches the end of the array, the loop operation ends. In this code, the variable $ element is an array. When each () is called, it returns an array with four values and four indexes pointing to the array position. Location key and 0 contain keywords of the current element, while location value and 1 contain the value of the current element. Although this is no different from the method selected, we chose to use the naming location instead of the numerical index location. In addition, there is a more advanced and common way to perform the same operation. The list () function can be used to break an array into a series of values. You can separate the two values returned by the function each () as follows:

  1. List ($ product, $ price) = each ($ price );

The above code uses each () to retrieve the current element from the $ prices array, return it as an array, and then point to the next element. It also uses list () to change the elements 0 and 1 in the array returned by each () to two new Manets named $ product and $ price. We can traverse the entire $ prices array cyclically and use the following short script to display its content:

  1. While (list ($ prodct, $ pirce) = each ($ prices ))
  2. Echo "$ product-$ price
    ";

The output result of this code is the same as the output result of the preceding script, but it is easier to read, because list () allows naming of new variables. Note that when using the each () function, the array records the current element. If you want to use the array twice in the same script, you must use the reset () function to reset the current element to the beginning of the array. To traverse the prices array again, use the following code:

  1. Reset ($ prices );
  2. While (list ($ product, $ price) = each ($ prices ))
  3. Echo "$ product-$ price
    ";

3.4 array operator + Union, = equivalent, = constant ,! = Not equivalent, <> not equivalent ,! = Not constant. The union operator tries to add the elements in $ B to the end of $. If the elements in $ B have the same index as those in $ a, they will not be added. That is, the elements in $ a will not be overwritten.

3.5 multi-dimensional array arrays are not necessarily a simple list of keywords and values-each position in the array can also save another array. Using this method, you can create a two-dimensional array. A two-dimensional array can be regarded as a matrix, or a network with width and height, or rows and columns.

3.6 array sorting

3.6.1 the sort () function is case sensitive. All letters are in front of lowercase letters. So 'A' is less than 'z', while 'Z' is less than 'A '. The second parameter of the function is optional. This optional parameter can be set to SORT_REGULAR (default), SORT_NUMERIC, or SORT_STRING. The function of specifying the sort type is very useful, for example, when you want to compare strings that may contain numbers 2 and 12. From a mathematical perspective, 2 is smaller than 12, but as a string, '12' is smaller than '2 '.

3.6.2 use the asort () function and ksort () function to sort the related array sorting function asort () according to each element value of the array. The ksort () function sorts by keywords rather than by values.

3.6.3 reverse sorting function rsort () sorts a one-dimensional numeric index array in descending order. The arsort () function sorts a one-dimensional array in descending order of each element value. The krsort () function sorts one-dimensional arrays in descending order based on the keywords of the array elements. To access data in a one-dimensional array, you need to use the array name and element index. apart from an element with two indexes-rows and columns, two-dimensional arrays and one-dimensional arrays are similar. You can use a dual for loop to achieve the same effect:

  1. For ($ row = 0; $ row <3; $ row ++)
  2. {
  3. For ($ column = 0; $ column <3; $ column ++)
  4. {
  5. Echo '|'. $ products [$ row] [$ column];
  6. |
  7. Echo '|
    ';
  8. }

If you use this code for a large array, it will be much simpler. You may prefer to create column names instead of numbers. You can use the following code:

  1. $ Products = array ('code' => 'tire', 'desserption '=> 'tires', 'price' => 100 ), array ('code' => 'oil ', 'descr resume ption' => 'oil ', 'price' => 10 ), array ('code' => 'spk', 'desscr resume ption '=> 'spark S s', 'price' => 4 )};

If you want to retrieve a single value, it is much easier to use this array. Remember to save the description to a column named by its name, which is easier to remember than saving it to the so-called first column. When using descriptive indexes, you do not need to remember that an element is stored at [x] [y. You can use a meaningful row or column name as an index to easily find the required data. Then, we cannot use a simple for loop to traverse each column in order. You can use the for loop to traverse the external data index array $ products. Each row of the $ products array is an array with descriptive indexes. You can use the each () and list () functions in the while loop to traverse the entire internal array. Therefore, a for loop embedded with a while loop is required.

  1. For ($ row = 0; $ row <3; $ row ++}
  2. {
  3. While (list ($ key, $ value) = each ($ products [$ row])
  4. {
  5. Echo "| $ value ";
  6. }
  7. Echo '|
    ';
  8. }

3D arrays have the concept of height, width, and depth. If you can easily think of a two-dimensional array as a table with rows and columns, you can think of a three-dimensional array as a heap of tables like this. Each element can be referenced through layers, rows, and columns. You can create a four-dimensional, five-dimensional, or six-dimensional array based on the method for creating a multi-dimensional array. In PHP, there is no limit on array dimensions, but it is difficult to imagine an array with more than three dimensions. Most of the actual problems logically only require an array structure of three or fewer dimensions.

3.7 multi-dimensional array sorting is much more complicated to sort more than one-dimensional arrays, or not sort by letters or numbers. PHP knows how to compare two numbers or strings, but in multi-dimensional arrays, each element is an array. PHP does not know how to compare two arrays, so we need to establish a method to compare them. In most cases, the order of words and numbers is obvious-but for complex objects, there are more problems.

3.7.1 "u" in user-defined sorting usort () indicates "user", because this function requires passing in user-defined comparison functions. The versions uasort () and uksort () corresponding to asort and ksort also require that user-defined comparison functions be passed in. Similar to asort (), uasort () is used only when the values of non-numeric index arrays are sorted. If the value is a simple number or text, you can use asort. If the value to be compared is as complex as an array, you can define a comparison function and then use uasort (). Similar to ksort (), uksort () is used only when the keywords of the non-numeric index array are sorted (). If the value is a simple number or text, ksort is used. If the objects to be compared are as complex as arrays, you can define a comparison function and then use uksort ().

3.7.2 The reverse user sorting functions sort (), asort (), and ksort () correspond to a reverse sorting function with the letter "r" respectively. User-defined sorting does not have reverse variants, but a multi-dimensional array can be sorted in reverse order.

3.8 sort the array again

3.8.1 in earlier versions of PHP, shuffle () requires a random number generator to be provided when calling the srand () function. Now, this step is no longer needed. If this function is very important to you, you can test it on the server before applying it in the program. Because you do not need to re-sort the entire array, you can use the array_rand () function to implement the same function.

3.8.2 use the array_reverse () function array_reverse () to use an array as a parameter and return an array with the same content as the parameter array but in the opposite order. Because the range () function is used separately to create an ascending sequence, you must use the sort () function or the array_reverse () function to change the number in the array to a descending order. Alternatively, you can use the for loop to create this array with one element at a time. For example:

  1. $ Numbers = array ();
  2. For ($ I = 10; $ I> 0; $ I --)
  3. Array_push ($ numbers, $ I );

A for loop can run in descending order like this. You can run a for loop on the counter in descending order like this. You can set the initial value of a counter to a large number, and use the "--" operator at the end of each loop to reduce the counter by 1. Here, we create an empty array and use the array_push () function to add each new element to the end of the array. Note that the function opposite to array_push () is array_pop (). This function is used to delete and return an element at the end of the array. Alternatively, you can use the array_reverse () function to reverse sort the array created by the range () function. Note that the array_reverse () function returns a modified copy of the original array. If you no longer need the original array, for example, in this example, you can use a new copy to overwrite the original version. If the data is only a series of integers, you can create the array in reverse order by using-1 as the third optional parameter of the range () function.

3.9 load an array from a file using the file () function to load the entire file into an array. Each row in the file becomes an element in the array. The count () function is used to count the number of elements in the array. The explode ("\ t", $ orders [$ I]) explode () function can split input strings into small pieces. Each tab is a breakpoint between two elements. The optional parameter limit of this function can be used to limit the maximum number of returned blocks. You can use many methods to extract numbers from strings. Here, we use the intval () function. It can convert a string into an integer. This conversion is quite intelligent. it can ignore some parts. for example, tags cannot be converted into numbers.

3.10 perform other array operations

3.10.1 browsing in arrays: each (), current (), reset (), end (), next (), pos (), and prev () as mentioned earlier, each array has an internal pointer pointing to the current element in the array. When the function each () is used, the pointer is used indirectly, but the pointer can be directly used and operated. If you create a new array, the current pointer is initialized and points to the first element of the array. Calling next () or each () will move the pointer forward to an element. Calling each ($ array_name) will return the current element before the pointer moves forward. The next () function is somewhat different-calling next ($ array_name) is to move the pointer forward and then return the new current element. Call end ($ array_name) to move the pointer to the end of the array. To traverse an array in reverse direction, you can use the end () and prev () functions. The prev () function is opposite to the next () function. It moves the current pointer back to a position and then returns the new current element.

3.10.2 apply any function to each element of the array: the array_walk () function requires three parameters. The first one is arr, which is the array to be processed. The second is func, which is the function that the user defines and acts on each element in the array. The third parameter userdata is optional. if it is used, it can be passed to our own function as a parameter. Let's look at an example of the complexity of sales:

  1. Function my_multiply (& $ value, $ key, $ factor)
  2. {
  3. $ Value * = $ factor;
  4. }
  5. Array_walk (& $ array, 'My _ multiply', 3 );

Here, we define a function named my_multiply (), which can be multiplied by each element in the array by the provided multiplication factor. In addition, you need to pay attention to the method of passing the number of workers $ value. In the function definition of my_multiply (), the address character (&) before the variable means that $ value is passed by reference. Pass the content that allows the function to modify the array in reference mode.

3.10.3 count the number of array elements: the count (), sizeof (), and array_count_values () count () functions have the same purpose as the sizeof () functions. both functions can return the number of array elements. We can get the number of elements in a regular scalar variable. If the array passed to this function is an empty array or an unspecified variable, the number of returned arrays is 0. If array_count_values ($ array) is called, this function counts the number of times each specific value has exceeded in the array $ array (this is the base set of the array ). This function returns an array containing the frequency table. This array contains all values in the array $ array and uses these values as the keywords of the related array. The value corresponding to each keyword is the number of times the keyword appears in the array $ array.

3.10.4 convert an array to a scalar variable: extract () for a non-numeric index array, which has many key-value pairs. you can use the extract () function () convert them into a series of scalar variables. The function extract () is used to create a series of scalar variables through an array. the names of these variables must be the names of the keywords in the array, and the value of the variable must be the values in the array. The extract () function has two optional parameters: extract_type and prefix. The variable extract_type tells the extract () function how to handle conflicts. Sometimes there may already be a variable with the same name as the array keyword. the default operation of this function is to overwrite the existing variable. The two most common options are EXTR_OVERWRITE (default) and EXTR_PREFIX_ALL. Other options may be used when you know that a specific conflict will occur and you want to skip this keyword or add a prefix to it. Extract () can extract an element. the keyword of this element must be a valid variable name, which means that the keyword that starts with a number or contains spaces will be skipped.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.