PHP two-dimensional array deduplication algorithm, PHP two-dimensional array deduplication Algorithm
Requirement
The following two-dimensional array is available:
Array (8) {[0] => array (2) {["name"] => string (4) "name" ["value"] => string (6) "qingye"} [1] => array (2) {["name"] => string (5) "phone" ["value"] => string (11) "13812341234"} [2] => array (2) {["name"] => string (12) "fileds_507 []" ["value"] => string (12) "I am qingye"} [3] => array (2) {["name"] => string (12) "fileds_508 []" ["value"] => string (6) "Hefei"} [4] => array (2) {["name"] => string (12) "fileds_509 []" ["value"] => string (3) "male"} [5] => array (2) {["name"] => string (12) "fileds_510 []" ["value"] => string (6) "soccer"} [6] => array (2) {["name"] => string (12) "fileds_510 []" ["value"] => string (6) "Baseball"} [7] => array (2) {["name"] => string (12) "fileds_511 []" ["value"] => string (16) "2016-12-15T11: 15 "}}
You need to merge the values of the arrays with the same name and value to form a new array.
For example, the two-dimensional arrays whose name is fileds_510 in the above Code should be merged into an array whose value is football and baseball.
Ideas
When it comes to arrays, we first think of loops in PHP, so here it is obviously better to use for loop processing. It is similar to Bubble sorting, and it is better to compare them one by one.
Code
The Code is as follows:
$ Public_info = array; for ($ I = 0; $ I <count ($ public_info); $ I ++) {for ($ j = $ I + 1; $ j <count ($ public_info); $ j ++) {if ($ public_info [$ j] ['name'] = $ public_info [$ I] ['name']) {$ public_info [$ I] ['value']. = ','. $ public_info [$ j] ['value']; unset ($ public_info [$ j]) ;}}
Execution result:
Array (7) {[0] => array (2) {["name"] => string (4) "name" ["value"] => string (6) "qingye"} [1] => array (2) {["name"] => string (5) "phone" ["value"] => string (11) "13812341234"} [2] => array (2) {["name"] => string (12) "fileds_507 []" ["value"] => string (12) "I am qingye"} [3] => array (2) {["name"] => string (12) "fileds_508 []" ["value"] => string (6) "Hefei"} [4] => array (2) {["name"] => string (12) "fileds_509 []" ["value"] => string (3) "male"} [5] => array (2) {["name"] => string (12) "fileds_510 []" ["value"] => string (13) "soccer, baseball "} [7] => array (2) {[" name "] => string (12)" fileds_511 [] "[" value "] => string (16) "2016-12-15T11: 15 "}}
Summary
The requirement has been fixed. As long as an array is encountered, the first thing we think of is a loop in addition to the ready-made PHP method, whether it is foreach or, the above example is a short process of custom form editing in my project. I hope it will be helpful for your ideas.