Reputation: 670
I have three arrays like so
$wages = array("Tom" => "£20", "Mike" => "£5.60", "James" => "12");
$training = array("Tom" => "£2", "James" => "7", "Dean" => "£3.50");
$tax = array("James" => "£1.50", "Kevin" => "£3", "Dean" => "£2");
Each array has the wages/training/tax for every employee. What I'm trying to do is separate them out so that I can have a single array for each employee. Desired result would be in the format of employee => (wages, training, tax)
:
$array1 = array("Tom" => "£20", "£2", "0");
$array2 = array("Mike" => "£5.60", "0", "0");
$array3 = array("James" => "£12", "£7", "£1.50");
The reason I am doing this, is because I want to write the result to a spreadsheet via CSV (fputcsv
). Now, I have been trying to reorganise like so:
First combing the array to have both key and value the same.
$combined = array_combine($employeesList, $employeesList);
employeesList
only contains the names of the employees as values.
Then looping through this employees array to see if any of the keys exist in the arrays defined above like so:
foreach ($employeesList as $employee) {
if (array_key_exists($employee, $wages))
$combined[$employee] = array($employee, $wages[$employee]);
}
}
This part works fine. Then I do it for the tax array like so:
foreach ($tax as $key => $value) {
if (array_key_exists($key, $combined)) {
array_push($combined[$key], $value);
}
But this fails at the second iteration saying that array_push
is expecting an array when string is given. Like the arrays above show, not every employee will have a record for every field. So i'm wondering how I can fix this? And/or if there is an alternative route to the one I'm taking. Any help is appreciated
Upvotes: 1
Views: 55
Reputation: 2633
First extract all of the names
$names = array_unique(array_merge(array_keys($wages), array_keys($training), array_keys($tax)));
Then iterate over the names to generate the record set
$employeeList = [];
foreach ($names AS $name)
$employeeList[$name] = [@$wages[$name] ?: 0, @$training[$name] ?: 0, @$tax[$name] ?: 0];
Note the error suppression with @
... this is performed because we don't care when individual values are missing; a default is provided.
Which will result in a set like the following
> var_dump($employeeList);
array(5) {
["Tom"]=>
array(3) {
[0]=>
string(4) "£20"
[1]=>
string(3) "£2"
[2]=>
int(0)
}
["Mike"]=>
array(3) {
[0]=>
string(6) "£5.60"
[1]=>
int(0)
[2]=>
int(0)
}
["James"]=>
array(3) {
[0]=>
string(2) "12"
[1]=>
string(1) "7"
[2]=>
string(6) "£1.50"
}
["Kevin"]=>
array(3) {
[0]=>
int(0)
[1]=>
int(0)
[2]=>
string(3) "£3"
}
["Dean"]=>
array(3) {
[0]=>
int(0)
[1]=>
string(6) "£3.50"
[2]=>
string(3) "£2"
}
}
Upvotes: 1