-1

我有两个数组:-

$a1=array(1,1,2,3,1);<br>
$a2=array("m","m","s","xl","s");

我想要这个作为输出我应该怎么做:-

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => m
            [2] => 2 //this is count of m
        )
    [1] => Array
        (
            [0] => 1
            [1] => s
            [2] => 1 //this is count of s
        )
    [2] => Array
        (
            [0] => 2
            [1] => s
            [2] => 1 //this is count of s
        )
    [3] => Array
        (
            [0] => 3
            [1] => xl
            [2] => 1 //this is count of xl
        )
)
4

1 回答 1

0

您可以通过循环输入数组并[1, m, 1]根据第一组值($a1[0]$a1[0])直接将元素放入结果数组中来做到这一点。然后在下一轮中,您必须检查您的结果数组是否已经包含具有当前产品 ID 和大小的项目 - 如果是,则在此处增加计数器,如果不是,则需要创建一个新元素。但是检查这样的项目是否已经存在会有点痛苦,因为基本上你每次都必须循环遍历所有现有的项目才能这样做。

我更喜欢先使用不同的临时结构来收集必要的数据,然后在第二步将其转换为所需的结果。

$a1=array(1,1,2,3,1);
$a2=array("m","m","s","xl","s");

$temp = [];
foreach($a1 as $index => $product_id) {
  $size = $a2[$index];
  // if an entry for given product id and size combination already exists, then the current
  // counter value is incremented by 1; otherwise it gets initialized with 1
  $temp[$product_id][$size] = isset($temp[$product_id][$size]) ? $temp[$product_id][$size]+1 : 1;
}

这给出了以下形式的 $temp 数组:

array (size=3)
  1 => 
    array (size=2)
      'm' => int 2
      's' => int 1
  2 => 
    array (size=1)
      's' => int 1
  3 => 
    array (size=1)
      'xl' => int 1

您会看到产品 id 是顶层的键,然后尺寸是第二层的键,第二层的值是产品 id 和尺寸组合的计数。

现在我们将其转换为您想要的结果结构:

$result = [];
foreach($temp as $product_id => $size_data) {
  foreach($size_data as $size => $count) {
    $result[] = [$product_id, $size, $count];
  }
}
var_dump($result);
于 2019-11-06T13:01:29.817 回答