i have two arrays :-
$a1=array(1,1,2,3,1);<br>
$a2=array("m","m","s","xl","s");
i want this as output what should i do :-
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
)
)
You could do this by looping over your input arrays, and directly putting an element [1, m, 1]
into your result array based on the first set of values ($a1[0]
and $a1[0]
). Then in the next round, you would have to check if your result array already contains an item with the current product id and size - if so, you increment the counter there, if not, you need to create a new element. But checking if such an item already exists is going to be a bit painful then, because basically you would have to loop over all existing items each time again to do so.
I prefer to go with a different, temporary structure first to gather the necessary data, and then transform it into the desired result in a second step.
$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;
}
That gives a $temp array of the following form:
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
You see the product id is the key on the top level, then the size is the key on the second level, and the value on the second level is the count for that combination of product id and size.
Now we transform that into your desired result structure:
$result = [];
foreach($temp as $product_id => $size_data) {
foreach($size_data as $size => $count) {
$result[] = [$product_id, $size, $count];
}
}
var_dump($result);