0

I want to count the rows based on like and unlike value in an array.I want to count the rows based on like and unlike value.I need to display like:3 and unlike:1.Now it display like:0,unlike:0 '$content' value is either {"userid":"1","like":"1"} or {"userid":"1","unlike":"1"}

enter image description here

$like_count     = 0;
$unlike_count   = 0;
while($like_fet = mysql_fetch_assoc($query))
{
    $content    = $like_fet['CONTENT_VALUE'];
    $datas  = json_decode($content);
    foreach($datas as $item)
    {
        $like    = $item['like'];
        $unlike = $item['unlike'];
        if($like != '' && $unlike == '')
        {
            echo "like";
            $like_count++;  
        }
        if($unlike != '' && $like == '')
        {
            echo "unlike";
            $unlike_count++;  
        }
    }
}
4
  • Is there a reason/design why you store that inforamtion as json in your mysql database? Commented Dec 7, 2015 at 7:37
  • ya I have some reason to do like this Commented Dec 7, 2015 at 7:39
  • better you would have used boolean value for like and unlike . Commented Dec 7, 2015 at 7:40
  • "ya I have some reason to do like this" - No offense but ... I'm presumptuous enough to assume "some" means "not a very good" ;-) But anyway.... No, seriously; there might be a good reason - it just doesn't often show here on stackoverflow/[php] :D Commented Dec 7, 2015 at 7:43

1 Answer 1

2
$like_count=0;
$unlike_count=0;
while($like_fet=mysql_fetch_assoc($query)) {
    $json = json_decode($like_fet['CONTENT_VALUE'], true);
    if ( isset($json['like']) ) {
        $like_count += $json['like'];
    }
    if ( isset($json['unlike']) ) {
        $unlike_count += $json['unlike'];
    }
}

depending on how CONTENT_VALUE actually works this can probably simplified to

$like_count=0;
$unlike_count=0;
while($like_fet=mysql_fetch_assoc($query)) {
    $json = json_decode($like_fet['CONTENT_VALUE'], true);
    if ( isset($json['like']) ) {
        $like_count++;
    }
    else if ( isset($json['unlike']) ) {
        $unlike_count++;
    }
    else {
        trigger_error('CONTENT_VALUE without like/unlike element', E_USER_NOTICE);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I caught error as '<b>Fatal error</b>: Cannot use object of type stdClass as array'
yeah, sorry - I forgot the , true on json_decode to get an array instead of an object.

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.