In PHP, the two-dimensional array can be used to sort, convert, and remove blank items.

Source: Internet
Author: User
In PHP, the two-dimensional array deduplication note-similar to other php processing of the two-dimensional array _ sorting, conversion, removal of white space, etc. PHP provides the array_unique function to remove repeated items in the one-dimensional array, however, in actual project development, the arrays queried from the select database are often 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 removes the duplicate two-dimensional array.


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 after deduplication

Foreach ($ tempnew as $ tempkey => $ tempval)
$ Output [$ k] [$ keyname_Arr [$ tempkey] = $ tempval;
}

Cion. recorded on

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.