update: edited question incorrectly, it's fixed now
let's have following associative array:
array ( [postponement no issue man utd (bbc) ] => 8 [postponement no issue man utd ] => 7 [postponement no issue man utd: manchester united have no issue on sunday's game @ chelsea being ... ] => 3 )
you'll notice term "postponement no issue man utd" appears in 3 keys. want turn array new array this:
array ( [postponement no issue man utd] => 18 )
where 18 sum of values key contains "postponement no issue man utd".
in other words: if 1 key appears inside key, latter dropped fom new array , it's value added on former key's value.
is possible , how? in advance.
depending on size of data may not feasible. there more optimal solution, works:
<?php $array = array( 'postponement no issue man utd (bbc)' => 8, 'postponement no issue man utd' => 7, 'postponement no issue man utd: manchester united have no issue on sunday\'s game @ chelsea being ...' => 3 ); $keys = array_keys($array); usort($keys, 'lengthcmp'); $flippedkeys = array_flip($keys); $data = array(); foreach ($keys $k => $v) { $sum = 0; foreach ($array $key => $val) { if (stripos($key, $v) !== false) { $sum += $val; unset($array[$key]); unset($keys[$flippedkeys[$v]]); } } $data[$v] = $sum; } foreach ($data $key => $val) { if ($val == 0) unset($data[$key]); } var_dump($data); function lengthcmp($a, $b) { return strlen($a) - strlen($b); } ?>
output:
array(1) {["postponement no issue man utd"] => int(18)}
and data set:
$array = array( 'test test' => 1, 'postponement no issue man utd (bbc)' => 8, 'postponement no issue man utd' => 7, 'postponement no issue man utd: manchester united have no issue on sunday\'s game @ chelsea being ...' => 3, 'test' => 1, 'not here' => 1, 'another test' => 1 );
output:
array(3) { ["test"] => int(3) ["not here"] => int(1) ["postponement no issue man utd"] => int(18) }
Comments
Post a Comment