-1

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?

ADyson
  • 57,178
  • 14
  • 51
  • 63
John
  • 51
  • 5
  • 4
    Keys in a array are `unique`, so you can't set 'Test Product' x times. – Foobar Dec 16 '22 at 10:12
  • Your expected output isn't possible, as Foobar explained. – ADyson Dec 16 '22 at 10:16
  • The closest you can get is [this](https://3v4l.org/KmAXl). – ADyson Dec 16 '22 at 10:17
  • This smells potentially like an XY problem...what is the overall goal here? What were you planning to do with this combined array, once you had produced it? – ADyson Dec 16 '22 at 10:17
  • `correct approach` depends on what you want to do after. You can for example create the array manual an merge values e.g. `$array['Test Product'][]=1;` that will result in `array('Test Product'=>[1,2,5,..])`. Or you pack pairs like `$args[]=['Test Product',1];` what results in `array(['Test Product',1],['Test Product',2],['Test Product',3])`. For both version you use `foreach`. – Foobar Dec 16 '22 at 10:18
  • 2
    @Foobar i have updated the question . I want to take the sum of each product, as follows, [Test Product] => 22 [Hello world poduct] =>16 ... – John Dec 16 '22 at 10:19

2 Answers2

3

Here are three examples of how it can be done:

Data:

$a = array(
  2,
  3,
  10,
  3,
  4,
  8,
  5,
  1,
  1
);

$b = array(
  "Hello world poduct",
  "Test Product",
  "Hello world poduct",
  "Hello world poduct",
  "Test Product",
  "Test Product",
  "Test Product",
  "Test Product",
  "Test Product",
);
  1. (foreach)
#foreach usage
$result = [];
$numbers = $a;
$names = $b;
foreach ($names as $index => $name) {
    $result[$name] ??= 0;
    $result[$name] += $numbers[$index];
}
var_export($result, false);
  1. (for loop)
#for usage
$result = [];
for($i=0;$i<count($a);$i++){
    if(!isset($result[$b[$i]])){
        $result[$b[$i]] = 0;
    }
    $result[$b[$i]] += $a[$i];
}
var_export($result);
  1. (array walk)
#array_walk
$result = [];
array_walk($a,function($v,$i) use (&$result,$b) {
    if(!isset($result[$b[$i]])){
        $result[$b[$i]] = 0;
    }
    $result[$b[$i]] += $v;
});
var_export($result);

Live demo: https://3v4l.org/OeWln

Relevant documentation: https://www.php.net/manual/en/function.array-walk.php

ADyson
  • 57,178
  • 14
  • 51
  • 63
Foobar
  • 769
  • 1
  • 4
  • Good code. I updated with some useful stuff, clarified the content, and made it use the OP's data, so it's more relevant :-) – ADyson Dec 16 '22 at 10:36
  • I also removed the superfluous array keys and added the foreach example, it is normally the first form of iteration in PHP. – hakre Dec 16 '22 at 11:24
1

An even simpler approach:

$arr_a = [2, 3, 10, 3, 4, 8, 5, 1, 1];

$arr_b = [
  "Hello world poduct",
  "Test Product",
  "Hello world poduct",
  "Hello world poduct",
  "Test Product",
  "Test Product",
  "Test Product",
  "Test Product",
  "Test Product",
];

$result = [];
foreach ($arr_b as $key => $product) {
  $result[$product] = ($result[$product] ?? 0) + $arr_a[$key];

}

var_dump($result);

This gives you:

array(2) {
  ["Hello world poduct"]=>
  int(15)
  ["Test Product"]=>
  int(22)
}
user1915746
  • 466
  • 4
  • 16
  • I never really know if the OP uses PHP>=7.x, so i try not to use `?? 0`. – Foobar Dec 16 '22 at 10:48
  • 1
    7.x is end of life, so he should use something newer :-) – user1915746 Dec 16 '22 at 10:50
  • Sometimes you see old mysql instead of mysqli here on SO :-) – Foobar Dec 16 '22 at 10:56
  • 1
    @Foobar true, but it doesn't make it right! I think you're within your rights to assume they're using a supported version, or at least a reasonably recent version, of any language / platform they ask about here, unless it's specifically stated otherwise. (And often those who state otherwise get a stern warning about upgrading due to security reasons!). https://www.php.net/supported-versions.php shows currently supported versions of PHP, and https://www.php.net/supported-versions.php shows older ones. Anything less than 7.x is very out of date by now :-) – ADyson Dec 16 '22 at 11:03
  • @ADyson You are completly right. Im using php 8 and never go back. But there is a php5 flag on SO, wandering why not php7 and php8 exists. Any maybe there are providers that are still hosting old php versions. – Foobar Dec 16 '22 at 11:16
  • While in my book backwards compatible code would not be outright wrong (and even can be of benefit), it would not be a requirement unless written clearly in the question. This is not nitpicking so, also not just comparing (version) numbers: it is a huge difference when an answer actually promotes unsafe code, like mysql instead of mysqli (the former lacks parametrized queries). Not the case here. But the answer has problems defining `$arr_b ` (contains superfluous code and data) as well as accessing `$arr_a`. I wonder who upvotes that (honestly). – hakre Dec 16 '22 at 11:17
  • @Foobar there are [tag:php-7] and [tag:php-8] tags too. And several for specific point releases within each of those, as well. – ADyson Dec 16 '22 at 11:17
  • @ADyson Not listed here https://stackoverflow.com/tags/php/synonyms May thats the wrong place for looking. – Foobar Dec 16 '22 at 11:18
  • @Foobar yes it's the wrong place really. There is also a separate [tag:php-5] tag, and version numbers within that too. Better to search on the tag page. Tag synonyms are all mapped to a single tag, whereas these are separate, individual tags, so you can use them in combination with the main "php" tag when tagging a post. https://stackoverflow.com/tags – ADyson Dec 16 '22 at 11:20
  • @ADyson Thats why i never see this tags, im looking only for `[php]`. Thangs for the advice/tip. – Foobar Dec 16 '22 at 11:22
  • @hakre It seems to work well enough, though: https://3v4l.org/QeSPj . Feel free to add a better answer, if you have one :-) – ADyson Dec 16 '22 at 11:23
  • @ADyson: As much as we ask for the minimal reproducible example, you'd should also take the look at the answer if you'e a regular. /E: or "does work" can have the same semantics as "does not work" if you tick what I'm trying to say. – hakre Dec 16 '22 at 11:28
  • @hakre sorry I'm not sure what your point is. I already tidied up Foobar's answer. – ADyson Dec 16 '22 at 11:29
  • @ADyson: Well not that one, the one here we're commenting beneath. And yeah there I did as well (but it is certainly never enough) – hakre Dec 16 '22 at 11:41
  • @hakre I'm still not sure what you're getting at. Are you saying that this answer we're commenting under is inadequate in some way? Could you be more specific? – ADyson Dec 16 '22 at 11:44
  • @ADyson: Yes, but not specifically. I raised my question that I didn't understood the upvote. And also why it gets the comment flag on PHP version while the obvious inadequate syntax it contains is independent to the PHP version. But yeah, discussing the PHP version is easier. No problem if its done. – hakre Dec 16 '22 at 11:48
  • @hakre ok but you haven't really explained _why_ you don't understand the upvote. You made some vague allusions but not really a clear explanation. You then edited Foobar's answer instead of this one. Was it actually that answer you thought was problematic? It's a bit unclear. – ADyson Dec 16 '22 at 11:49
  • @ADyson: Okay, well, the reason why I don't understand the upvote - as far as that was not already clear - was that I wouldn't upvote it. This difference nurtured my interest in the upvote and my interest to learn more about it. – hakre Dec 16 '22 at 11:52
  • @hakre "I wouldn't upvote it" isn't an objective reason for why you don't understand someone else upvoting it. That's just stating an opinion, and isn't really useful or interesting to anyone else, in this context. You're not backing it up with any real information. I can't work out if you're being obtuse on purpose or not, so I'm going to end this conversation now. – ADyson Dec 16 '22 at 13:20
  • Well for me it is totally valid between human beings if they show interest in each others opinions. Often this is pretty helpful, much more than jumping to conclusions early. – hakre Dec 16 '22 at 13:45
  • @hakre I don't dispute that sharing opinions is valid in general. Of course, it's a natural and healthy part of human interaction. But this is Stackoverflow, not a chat room. We're supposed to be providing objective answers to questions, and clear information to each other. Talking in vague terms or expressing personal opinions without providing specific evidence is not productive towards those aims. – ADyson Dec 16 '22 at 14:14
  • It was objectively commented on that answer where objectively that person has done that and objectively asked as a question. Those are all facts and related both to the work as well as the actions with it. It may not fulfill everyones' favorite fetish. If you have doubts on the upvoters behaviour please address it directly. I only asked a question, I can live with not getting an answer, I'm also not pressing for it. It seems its more you than me to me. – hakre Dec 16 '22 at 14:17
  • @hakre you said `the answer has problems defining $arr_b (contains superfluous code and data) as well as accessing $arr_a`. You didn't define what was superfluous. You didn't define what the problem acessing the variables was. It's vague, and not helpful to anyone. Those variables, with those names, don't even appear in this answer, so it's hard to tell what you're even talking about. If you think that's clear or "objective" then it's a pretty odd definition of the word, really. Over and out :-) – ADyson Dec 16 '22 at 14:21
  • @hakre None of that occurs in this answer, though. Nor does that appear to have any relevance to the bit of comment I quoted above. – ADyson Dec 16 '22 at 14:29
  • Then I stand corrected and thanks you asked about it. – hakre Dec 16 '22 at 14:32