One blog per day | remove duplicate items from two-dimensional arrays in PHP

Source: Internet
Author: User
One blog per day | two-dimensional array removal of repeated items in PHP the array_unique function is provided in PHP to remove repeated items in one-dimensional array, but in our actual project development, the arrays queried from the select statement of the database are usually two-dimensional;

There may be repeated items, so we need to define the function to remove them.

Ideas:

1. first obtain the key name of the second-dimensional array and save it in an array (assuming the name is keyname_Arr );

2. use a symbol as a separator (for example, '-') to splice the key values in the two-dimensional array into a string to generate a temporary array;

3. use the [array_unique () function] to compare the generated temporary array and remove the same string;

4. re-assemble the array after deduplication into a two-dimensional array:

Use the [explode () function] cyclically in foreach () and split the string by the '-' separator;

At the same time, in foreach (), use a foreach ($ tempnew as $ tempk => $ tempv) for the [new temporary array tempnew] formed by the split string ),

Cyclic value assignment $ output [$ k] [$ keyname_Arr [$ tempk] = tempv;

6. finally, $ output is the two-dimensional array after deduplication.

Let's take a look at the actual code:

$ Keyname_Arr = array_keys (end ($ resource_arr )); // key name for storing the inner array // use '-' as the separator to concatenate the array into a string foreach ($ resource_arr as $ v) {$ v = join ("-", $ v); $ temp [] = $ v;} // remove the duplicate string, that is, the duplicate one-dimensional array $ temp = array_unique ($ temp ); // re-assemble the split array foreach ($ temp as $ k => $ v) {$ tempnew = explode ("-", $ v ); // split the string foreach ($ tempnew as $ tempkey => $ tempval) $ output [$ k] [$ keyname_Arr [$ tempkey] = $ tempval ;}

Cion. it is recorded on 2016/05/03.

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.