I have the following input array:
$arr = array(
'water' => array(0, 1, 2, 3, 4, 5),
'apple' => array(1, 5, 3, 4, 0, 0),
'beer' => array(0, 0, 0, 0, 0, 0)
);
Now I want to know which element has largest sum, so I have the following code:
$arrWeight = array();
foreach ($arr as $key => $value)
{
$arrWeight[$key] = is_array($value) ? array_sum($value) : 0;
}
Then, I want to sort array based on weight. That's easy.
arsort($arrWeight);
Now, I want to slice the original array ($arr
) based on generated weights and limit.
$arrAllowedKeys = array_slice($arrWeight, 0, self::METRICS_BREAKDOWN_LIMIT, true);
foreach ($arr as $key => $value)
{
if (!array_key_exists($key, $arrAllowedKeys))
{
unset($arr[$key]);
}
}
For example, if I have self::METRICS_BREAKDOWN_LIMIT
equals to 2, I'd expect the following output:
$arr = array(
'water' => array(0, 1, 2, 3, 4, 5),
'apple' => array(1, 5, 3, 4, 0, 0),
);
So, basically, the above solution is working, but I'm looking for better approach.