php codeigniter 中的单个数组到关联数组(组合数组)
Single arrays to associative array in 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
)
)
您可以通过遍历输入数组,并根据第一组值($a1[0]
和 $a1[0]
)直接将元素 [1, m, 1]
放入结果数组来实现此目的.然后在下一轮中,您将必须检查您的结果数组是否已包含具有当前产品 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);
我有两个数组:-
$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
)
)
您可以通过遍历输入数组,并根据第一组值($a1[0]
和 $a1[0]
)直接将元素 [1, m, 1]
放入结果数组来实现此目的.然后在下一轮中,您将必须检查您的结果数组是否已包含具有当前产品 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);