Home  >  Article  >  Backend Development  >  How to filter php array by fields

How to filter php array by fields

尚
Original
2019-10-30 11:15:345667browse

How to filter php array by fields

How to filter PHP arrays by fields:

1. Use foreach to traverse the array to filter data

foreach is often used in PHP to traverse arrays, and then process the elements in the array. Below, foreach is used to traverse the $arr array, and filter the content of the elements with the field con in the array to filter out no less than 200, and an array not larger than 500.

The code is as follows:

How to filter php array by fields

The result after running the above code is as follows:

How to filter php array by fields

2. Use the for loop to traverse the array to filter data

The for loop is also commonly used in PHP. It is mainly used to execute the specified code block in a loop until the conditions are not met to terminate execution. The following code implements filtering out arrays greater than 400 according to the con field and placing them into a new array $newarr.

How to filter php array by fields

The result after running the above code is as follows:

How to filter php array by fields

3. Use the array_filter function to implement the array by field Filter data

The array_filter function uses the callback function method to filter the values ​​in the array to filter out the required data. The following code implements filtering out arrays smaller than 300 and placing them into a new array $newarr.

How to filter php array by fields

The result after running the above code is as follows:

How to filter php array by fields

4. How to use a while loop to traverse the array Filter data

The while loop will execute the specified code block cyclically as long as the conditions are met. The following code implements filtering out arrays less than 500 according to the con field and placing them into a new array $newarr.

How to filter php array by fields

The result after running the above code is as follows:

How to filter php array by fields

Recommended: php server

The above is the detailed content of How to filter php array by fields. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn