I have two arrays as follows, Array a represents the quntites while array b stores the product names
Array A
array:9 [▼
0 => 2
1 => 3
2 => 10
3 => 3
4 => 4
5 => 8
6 => 5
7 => 1
8 => 1
]
Array B
array:9 [▼
0 => "Hello world poduct"
1 => "Test Product"
2 => "Hello world poduct"
3 => "Hello world poduct"
4 => "Test Product"
5 => "Test Product"
6 => "Test Product"
7 => "Test Product"
8 => "Test Product"
]
Now I’m trying to combine these two arrays and get the following output,
Array
(
[Hello world poduct] => 2
[Test Product] => 3
[Hello world poduct] => 10
[Hello world poduct] => 3
[Test Product] => 4
[Test Product] => 8
[Test Product] => 5
[Test Product] => 1
[Test Product] => 1
)
I tried using PHP’s array_combine()
function
array_combine($arr_a,$arr_b)
This is not giving me the expected output…What changes should I make in order to take the expected result…or what would be the correct approach creating new array with expected way…
UPDATE
My final goal is to take the products and their total as mentioned bellow,
Array(
[Test Product] => 22
[Hello world poduct] => 15
)
As @foobar mentioned in the comments, since my keys are not unique, what coould be the better way doing this?
2
Answers
Here are three examples of how it can be done:
Data:
Live demo: https://3v4l.org/OeWln
Relevant documentation: https://www.php.net/manual/en/function.array-walk.php
An even simpler approach:
This gives you: