I have an issue with two arrays that I need to combine, where the first array contains a list of campaign names ( page_data ) like
[
"Campaign 1",
"Campaign 2",
"Campaign 3"
]
and another array that contains number of leads for the campaigns. But this array will contain twice as many keys as the campaign array like this:
[
222,
342,
71,
33,
43,
665
]
It contains twice as many keys, because it will take leads from two different forms, so the values for key 0
and key 3
will be for campaign 1 and key 2
and key 4
will be for campaign 2. It will always be this way. If there are 5 campaigns, leads array will have 10 keys and key 0
and key 5
will be for campaign one, key 1
an key 6
for campaign 2, etc.
And then I have this piece of code to combine ( push ):
foreach (json_decode($result) as $key) {
foreach ($pages["page_data"] as $p => $pvalue) {
array_push(
$leadArray,
array(
"pageName" => $pvalue["form_name"],
"pageLeads" => $key[$p]
)
);
}
}
That will incorrectly make an array that looks something like:
[
"campaign 1" => 222,
"campaign 2" => 342,
"campaign 3" => 71
]
But that will only take keys 0,1,2 and so key 3,4,5 will not be in the array.
What I want is key 0 and key 3, key 1 and key 4, etc. in the leads array to be combined so the the new leads array will be
[
255,
386,
736
]
which I can then combine with the campaigns array as the number of keys from the two arrays will now match which will give me an array that looks like
[
"campaign 1" => 255,
"campaign 2" => 386,
"campaign 3" => 736
]
Use array_chunk function for split your second array and it will be easy to sum values.
When you use this function, your array will splitted into two arrays. In first array you will have values 0, 1, 2, and in second you will have 3, 4, 5 values. Now iterate through your first array, using keys you will have access to value pairs: 0-3, 1-4, 2-5.
Check out this code:
<?php
$array1 = [0 => "Campaign 1", 1 => "Campaign 2", 2 => "Campaign 3"];
$array2 = [0 => 222, 1 => 342, 2 => 71, 3 => 33, 4 => 43, 5 => 665];
$chunkedArray2 = array_chunk($array2, count($array1), false);
$result = [];
foreach($array1 as $key => $value) {
$result[$value] = $chunkedArray2[0][$key] + $chunkedArray2[1][$key];
}
var_dump($result);
And result is:
Array
(
[Campaign 1] => 255
[Campaign 2] => 385
[Campaign 3] => 736
)