0

In JSON with key "string" and "value":

'Something xxx something' = 10
'Something yyy something' = 20
'Something xxx something' = 30
'Something zzz something' = 40

The flow I want is:

find partial string inside string
if true
get sum of all its matched string's value
if false
return 0

What I tried is

if (strpos($string, 'xxx') == false){
        $value = array_sum(array_column($arrayjson['string'],'value'));
        continue;
    }
echo $value

But, what I am getting is

100
100

Expected result is 40

silver_river
  • 169
  • 1
  • 10

2 Answers2

3

The problem is that even though you check if the string contains xxx (BTW you should use !== false as it may return 0), you then use array_column() to extract all of the values and add them all up(which is why you get 100).

This loops over the data and adds only the rows that match your required string...

$data = [ ['string' => 'Something xxx something', 'value' => 10],
    ['string' => 'Something yyy something', 'value'  => 20],
    ['string' => 'Something xxx something', 'value'  => 30],
    ['string' => 'Something zzz something', 'value'  => 40]];

$total = 0;
foreach ( $data as $row )   {
    if (strpos($row['string'], 'xxx') !== false){
        $total += $row['value'];
    }
}
echo $total;
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Thank you Nigel. Actually I stumbled upon `foreach` before, but not working because my `if (strpos...` was actually inside another `for ($j = 0; $j < ...` loop function. But your explanation give me a bigger picture of my mistake; to replace my loop function with `foreach`. Thank you again. – silver_river Sep 27 '19 at 18:10
1

At a cost of more function calls and a minor drop in efficiency, you can avoid the use of temporary variables by nesting native functions. (I'd use Nigel's way though)

Code: (Demo)

echo array_sum(
         array_column(
             array_filter(
                 $arrayjson,
                 function($row) {
                     return strpos($row['string'], 'xxx') !== false;
                 }
             ),
             'value'
         )
     );
mickmackusa
  • 43,625
  • 12
  • 83
  • 136