根据数组对象计算行数

时间:2015-12-07 07:33:00

标签: php mysql

我想在数组中基于like和不同的值来计算行数。我想基于like和not值来计算行数。我需要显示如下:3并且不像:1。现在它显示为:0 ,不像:0'$ content'值为{"userid":"1","like":"1"}{"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++;  
        }
    }
}

1 个答案:

答案 0 :(得分: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'];
    }
}

取决于CONTENT_VALUE的实际工作方式,这可能会简化为

$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);
    }
}