Detailed graphic explanation of the method of converting an array vertically to horizontally and filtering duplicate values ​​in PHP

墨辰丷
Release: 2023-03-27 10:50:01
Original
1329 people have browsed it

This article mainly introduces the method of PHP to realize vertical conversion of arrays to horizontal and filter duplicate values. Combined with specific examples, it compares and analyzes PHP's operating skills related to array traversal, conversion and deduplication. Friends who need it can refer to it

The details are as follows:

1. Question

There is an array:


array(
  6=>array(5=>'黑xx', 42=>'XXL'),
  7=>array(5=>'黑xx', 40=>'XL'),
  8=>array(8=>'灰',  40=>'XL'),
);
Copy after login


is required to be converted into the following result (the array is turned vertically and horizontally and duplicate values ​​are filtered):


array(
  0=>array(5=>'黑xx', 8=>'灰'),
  1=>array(42=>'XXL', 40=>'XL'),
);
Copy after login


2. Solution:

Method 1:


$a = array(
  6=>array(5=>'黑xx', 42=>'XXL'),
  7=>array(5=>'黑xx', 40=>'XL'),
  8=>array(8=>'灰',  40=>'XL'),
);
foreach($a as $r) {
 $b[key($r)] = current($r);
 next($r);
 $c[key($r)] = current($r);
}
$b = array($b, $c);
print_r($b);
Copy after login


Method 2:


$arr = array(
  6=>array(5=>'黑xx', 42=>'XXL'),
  7=>array(5=>'黑xx', 40=>'XL'),
  8=>array(8=>'灰',  40=>'XL'),
);
$result = array();
foreach($arr as $a){
  $keys = array_keys($a);
  $vals = array_values($a);
  $result[0][$keys[0]] = $vals[0];
  $result[1][$keys[1]] = $vals[1];
}
print_r($result);
Copy after login


The simplest Writing method:


$a = array(
  6=>array(5=>'黑xx', 42=>'XXL'),
  7=>array(5=>'黑xx', 40=>'XL'),
  8=>array(8=>'灰',  40=>'XL'),
);
foreach($a as $r) {
 $i = 0;
 while(list($k, $v) = each($r)) $b[$i++][$k] = $v;
}
print_r($b);
Copy after login


The final running results are:


Array
(
  [0] => Array
    (
      [5] => 黑xx
      [8] => 灰
    )
  [1] => Array
    (
      [42] => XXL
      [40] => XL
    )
)
Copy after login



Related recommendations:

PHP Practical TutorialFiltering, verification, escaping and password Method

About PHP FilterRelated knowledge

php security Filter


The above is the detailed content of Detailed graphic explanation of the method of converting an array vertically to horizontally and filtering duplicate values ​​in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template