Group array by keys value
I have searched around and I am at my wits end so I will make this easy. This is what I have in a print_r:
Array
(
[0] => Array
(
[name] => client interaction
[y] => 2.7
)
[1] => Array
(
[name] => client interaction
开发者_高级运维 [y] => 0.1
)
[2] => Array
(
[name] => project planning
[y] => 0.1
)
[3] => Array
(
[name] => client interaction
[y] => 5.9
)
)
And this is what I want it to be:
Array
(
[0] => Array
(
[name] => client interaction
[y] => 8.7
)
[1] => Array
(
[name] => project planning
[y] => 0.1
)
)
Is it absolutely necessary that your desired array use numeric indeces? If I were to do this I would do it this way (not the same as your desired array though)
$newArray = array();
foreach($array as $item)
{
if(!isset($newArray[$item["name"]]))
$newArray[$item["name"]] = 0;
$newArray[$item["name"]] += $item["y"];
}
This will give you an array of this structure:
Array
(
[client interaction] => 8.7
[project planning] => 0.1
)
To get the keys back you simply use the second form of the foreach
loop
foreach($newArray as $name => $y)
$name
will contain the name
and $y
the y
in your original array.
$hash = array();
foreach ($sourceArray as $key=>$value) {
$y = 0;
if (isset($hash{$value{'name'}})) {
$y = $hash{$value{'name'}};
}
$hash{$value{'name'}} = $y + $value{'y'};
}
$result = array();
foreach ($hash as $key => $value) {
$result[] = array( 'name' => $key, 'value' => $value );
}
print_r($result);
The last loop is just to get $hash
into the exact format you specified.
Explanation:
$hash
Is a temporary structure used to compute the sums for each unique name.
foreach ($sourceArray as $key=>$value) {
This goes through your original array ($sourceArray) and pulls out each element.
$y = 0;
Initializes a variable to store the current sum that belongs with that name.
if (isset($hash{$value{'name'}})) {
Checks to see if a value has already been stored in $hash
for the given name.
$y = $hash{$value{'name'}};
}
Sets $y to the previously calculated sum for the given name, if there was one.
$hash{$value{'name'}} = $y + $value{'y'};
}
Stores the sum for the given name into our temporary structure $hash
.
$result = array();
foreach ($hash as $key => $value) {
$result[] = array( 'name' => $key, 'value' => $value );
}
converts $hash to the format you desired.
The empy []'s in $result[] = ...
add the right hand side of the expression to the end of the $result
array.
$mixed = array(); // Should contain your array shown above
$groups = array();
$newArray = array(); // Will contain your new array
$counter = 0;
foreach( $mixed as $mix )
{
if ( isset($groups[$mix['name']]) )
{
$newArray[$groups[$mix['name']]]['y'] += $mix['y'];
}
else
{
$groups[$mix['name']] = $counter;
$newArray[] = $mix;
$counter++;
}
}
http://codepad.org/EjdHxgvt
精彩评论