0

Please see table below:

items

id  title   fields
1   Dog     [{"id":"11","value":"50"},{"id":"19","value":"100"},{"id":"22","value":"150"}]
2   Cat     [{"id":"19","value":"50"},{"id":"22","value":"100"},{"id":"37","value":"150"}]
3   Bird    [{"id":"14","value":"50"},{"id":"19","value":"100"},{"id":"22","value":"150"}]
4   Mouse   [{"id":"16","value":"50"},{"id":"22","value":"100"},{"id":"34","value":"150"}]
5   Horse   [{"id":"6","value":"50"},{"id":"22","value":"100"},{"id":"47","value":"150"}]

I want to echo the sum of all the values that equals to id 22 I am a complete novice to php and mysql and will appreciate any assistance, so please explain the code to me clearly.

This is what I have found, but does not work:

<?php
    if ($fields->id == 22) {
        $result += $fields['value'];
    }
    return $result;
?>

please help.... thank you

4
  • Do "var_dump($array);" and post the result in your question above please. Commented Jan 9, 2014 at 10:56
  • can you show what is the result of var_dump($fields);Also i guess you need to loop throught he items and find the sum. Commented Jan 9, 2014 at 10:57
  • are the values json_encoded? What does your actual array look like? Commented Jan 9, 2014 at 10:59
  • after investigation i can confirm that it is json data and that i've tried Sankalp's answer, but with no success. You refer to var_dump.... I have no idea what you are talking about or even where i need to enter that code. I did however add it to the php output file and the only result i received was NULL, if that makes any sense. I tried both answers below, but not working. Commented Jan 9, 2014 at 12:24

1 Answer 1

2

Looks like $fields is json data. If it is, then

Try this:

    $data = json_decode($fields);
    foreach($data as $element) {
      if ($fields->id == 22) {
         $result += intval($fields->value);
      }
    }
    return $result;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.