php codeigniter中的单个数组到关联数组(Combine Arrays)

我有两个数组:-

$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
        )
)
minm_in520 回答:php codeigniter中的单个数组到关联数组(Combine Arrays)

您可以通过循环输入数组,然后根据第一组值([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);
本文链接:https://www.f2er.com/3152411.html

大家都在问