代码之家  ›  专栏  ›  技术社区  ›  fightstarr20

PHP-对象数组中的唯一计数

  •  0
  • fightstarr20  · 技术社区  · 6 年前

    我有一个PHP数组,其中包含如下对象

    Array
    (
    [0] => stdClass Object
        (
            [label] => Test 1
            [session] => 2
        )
    
    [1] => stdClass Object
        (
            [label] => Test 2
            [session] => 2
        )
    
    [2] => stdClass Object
        (
            [label] => Test 3
            [session] => 42
        )
    
    [3] => stdClass Object
        (
            [label] => Test 4
            [session] => 9
        )
     )
    

    我正在尝试统计此阵列中的唯一会话数。当整个事情都是一个数组时,我可以做到这一点,但当数组包含对象时,我很难计算出来。

    我是否需要将对象转换为数组,或者是否有方法将数据转换为当前格式?

    4 回复  |  直到 6 年前
        1
  •  4
  •   mickmackusa Tom Green    4 年前

    https://www.php.net/manual/en/function.array-column.php :

    Version    Description
    
     7.0.0     Added the ability for the input parameter to be an array of objects.
    

    使用array\u column使用会话列值生成新密钥。这将有效地删除重复的密钥。

    代码:( Demo )

    $array = [
        (object)['label' => 'Test 1', 'session' => 2],
        (object)['label' => 'Test 2', 'session' => 2],
        (object)['label' => 'Test 3', 'session' => 42],
        (object)['label' => 'Test 4', 'session' => 9],
    ];
    echo sizeof(array_column($array, null, 'session'));
    

    输出:

    3
    

    或在循环中:

    foreach ($array as $obj) {
        $result[$obj->session] = null;
    }
    echo sizeof($result);
    

    这两种技术都避免了 array_unique 并利用阵列无法存储重复密钥这一事实。

        2
  •  1
  •   Bhumi Shah    6 年前

    我已经尝试了您的代码,并在这里创建了示例数据

    $comments= array();
    $comment = new stdClass;
    $comment->label = 'Test 1';
    $comment->session = '2';
    array_push($comments, $comment);
    $comment = new stdClass;
    $comment->label = 'Test 2';
    $comment->session = '2';
    array_push($comments, $comment);
    $comment = new stdClass;
    $comment->label = 'Test 3';
    $comment->session = '42';
    array_push($comments, $comment);
    $comment = new stdClass;
    $comment->label = 'Test 4';
    $comment->session = '9';
    array_push($comments, $comment);
    

    下面是我试图获取唯一值的代码。这样可以获得任何字段的唯一值

    $uniques = array();
    foreach ($comments as $obj) {
        $uniques[$obj->session] = $obj;
    }
    echo "<pre>";
    print_r($uniques);
    echo "</pre>";
    
        3
  •  1
  •   The fourth bird    6 年前

    您也可以使用 array_map 只保留 session 在数组中,然后使用 array_unique 删除重复条目,最后 count 独特的项目。

    例如,如果调用了数组变量 $array :

    $result = array_map(function($x){
        return $x->session;
    }, $array);
    
    echo count(array_unique($result));
    

    这将导致:

    3.

    Demo

        4
  •  -2
  •   Gaterde    6 年前

    可以使用访问数组中的对象 $array[0] 其中 0 表示对象。要访问“对象”属性,可以执行以下操作: $object->session

    要查看每个对象会话属性,可以执行以下操作:

    foreach ($array as $object) {
        echo $object->session . "<br/>";
    }